[英]Problem with Java InputStream's read method not reading the first few bytes
因此,我编写了一个简单的程序,它接收一个文本文件,并在单独的行上逐行处理文件中的字符。
下面是我正在使用的“hello.txt”文本文件的内容:
Hello How Are You?
这是我的代码:
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class input_stream {
public static void main(String args[]) throws FileNotFoundException, IOException {
InputStream input = new FileInputStream("C:\\Users\\m3hran\\Desktop\\file_test\\hello.txt");
byte[] byteArray = new byte[1024];
int ArraysRead = input.read(byteArray);
input.close();
System.out.println(ArraysRead);
for (byte i : byteArray) {
System.out.println ((char) i);
}
}
}
我的问题是我的 output 由于某种原因似乎跳过了前几个字节 - 这是我的 output:
我想知道是否有人知道是什么导致了这个问题? 任何帮助,将不胜感激!
第一次运行文件时,我得到的结果与您发布的结果相同,但在扩大终端并再次运行文件后,结果将正确显示,与外部相同终端:
这似乎是一个可以放在 github 中的问题,这是我的问题链接: Can't show complete java result in Terminal unless resize it 。
此外,请注意您的隐私保护,您可能会在截图中掩盖姓名。
您的代码应该没有问题,但我建议使用 try-with-resources 并使用您实际需要的长度初始化 arrays
String filePath = "C:\\Users\\m3hran\\Desktop\\file_test\\hello.txt";
File file = new File(filePath);
try(FileInputStream fis = new FileInputStream(file)){
byte[] bytes = new byte[(int) file.length()];
int bytesRead = fis.read(bytes);
for (byte i : bytes) {
System.out.println((char) i);
}
} catch (IOException e) {
e.printStackTrace();
}
也从 Java7 你可以只使用Files::readAllBytes
String filePath = "C:\\Users\\m3hran\\Desktop\\file_test\\hello.txt";
byte[] bytes = Files.readAllBytes(new File(filePath));
for (byte i : bytes) {
System.out.println((char) i);
}
下面的代码打印了太多行,并且您的控制台有最大行数限制
for (byte i : byteArray) {
System.out.println ((char) i);
}
你可以试试
public static void main(String[] args) throws IOException{
InputStream input = new FileInputStream("C:\\Users\\m3hran\\Desktop\\file_test\\hello.txt");
byte[] byteArray = new byte[1024];
int len = input.read(byteArray);
input.close();
System.out.println(new String(Arrays.copyOf(byteArray,len)));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.