java - Input Streams.read() 它究竟是如何工作的?

标签 java stream inputstream

我有以下代码:

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 :

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 Stackoverflow

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.


因此,FileInputStreambyte 读取数据byte

关于java - Input Streams.read() 它究竟是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59987086/

相关文章:

java - 如何在 SWT 应用程序中显示 PDF?

C#/.net 相当于 android 处理程序

java - 我的对象列表应该有多大才能保证使用 java 8 的 parallelStream?

java - Android InputStream 互联网断开

java - 尝试连接到 URL 读取 xml 时出现错误 401

java - Apache Lucene QueryParser.parse 未在 FuzzyQuery 上使用分析器

testing - STREAM 基准的向量函数

java - Java 中的 mark() 和 reset() 方法

java - 使用 available() 时未获取完整数据

java - 为什么 javafx 应用程序无法使用 Platform.runLater 启动以及为什么会因 lambda 表达式而挂起?