我有以下代码:
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 doesinputStream.read()
read the filec:/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 thatFileInputStream#read
is used to read the byte of data from the input stream.
因此,FileInputStream
逐byte
读取数据byte
。
关于java - Input Streams.read() 它究竟是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59987086/