输入 Streams.read() 究竟是如何工作的呢?

Input Streams.read() How does it work exactly?

我有以下代码:

public static void main(String[] args) throws Exception {

 FileInputStream inputStream = new FileInputStream("c:/data.txt");

 FileOutputStream outputStream = new FileOutputStream("c:/result.txt");

 while (inputStream.available() > 0) {
  int data = inputStream.read(); 
  outputStream.write(data); 
 }

 inputStream.close(); 
 outputStream.close();
}

我不明白下面这行: int data = inputStream.read();

获取文件c:/data.txt的字节,逐字节读取,然后在可变数据中自动拼接或者inputStream.read()读取文件c:/data.txt全部立即将所有内容分配给数据变量?

来自 JavaDoc:

A FileInputStream 从文件系统中的文件获取输入字节。 FileInputStream 用于 读取原始字节流,例如图像数据 。 要读取 字符流 ,请考虑使用 FileReader

Question: Get the bytes of the file c:/data.txt, read byte by byte, and then get concatenated automatically within the variable data or does inputStream.read() read the file c:/data.txt all at once and assign everything to the data variable?

为了回答这个问题,让我们举个例子:

try {
  FileInputStream fin = new FileInputStream("c:/data.txt");
  int i = fin.read();
  System.out.print((char) i);
  fin.close();
} catch (Exception e) {
  System.out.println(e);
}

在 运行 上述程序之前创建了一个 data.txt 文件,其中包含以下文本:Welcome to Whosebug.

After the execution of above program the console prints single character from the file which is 87 (in byte form), clearly indicating that FileInputStream#read is used to read the byte of data from the input stream.


因此,FileInputStream 通过 byte 读取数据 byte