gpt4 book ai didi

java - FileInputStream 读取如何工作?

转载 作者:行者123 更新时间:2023-11-30 02:57:38 26 4
gpt4 key购买 nike

有人请解释一下如何在以下代码中填充缓冲区数组:

try {
byte[] buffer = new byte[1024];
//(1) this print an empty string?
System.out.println("1: " + new String(buffer));
FileInputStream inputStream = new FileInputStream("test.txt");
int len;

while((len = inputStream.read(buffer)) != -1) {
//(2) this print text on my file?
System.out.println("2: " + new String(buffer));
}
inputStream.close();

} catch (IOException e) {
e.printStackTrace();
}

更新:阅读以下内容后我得到了有用的信息: https://docs.oracle.com/javase/tutorial/essential/io/bytestreams.html

Buffered input streams read data from a memory area known as a buffer; the native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full

谢谢大家!

最佳答案

InputStream#read 方法会将数据从输入流读取到提供的缓冲区中。

请参阅java doc了解详情。

(特别是查看返回值 - 如果没有更多数据可供读取,它将返回 -1。)

关于java - FileInputStream 读取如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36802275/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com