文件输入流;为什么FileInputStream可以变成整数,有什么意义吗?
FileInputStream; Why can FileInputStream become an integer, does it have any meaning?
我正在某网站学习java,我发现了这个
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
c = in.read()) != -1
是什么意思?为什么可以是整数?
您使用了方法 FileInputStream.read()
(Oracle Doc ) 从文件
中读取 byte
并且((c = in.read()) != -1)
做了两件事
- 获取
in.read()
的值并存入c
(byte
转换为int
)
- 检查
c
是否与 -1
不同(如果等于 -1
则表示文件结束)
所以没有FileInputStream
变成了int
您的 FileInputStream
是一个字节流。
当您调用 FileInputStream.read()
时,它 return 来自流的 byte
或 return -1 如果到达流的末尾。
当你写:c = in.read()) != -1
、
- a
byte
从流中读取,扩展为 int
,分配回 c
和
- 通过比较 returned 值与
-1
; 来检查一个字节是否被成功读取
我正在某网站学习java,我发现了这个
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
c = in.read()) != -1
是什么意思?为什么可以是整数?
您使用了方法 FileInputStream.read()
(Oracle Doc ) 从文件
byte
并且((c = in.read()) != -1)
做了两件事
- 获取
in.read()
的值并存入c
(byte
转换为int
) - 检查
c
是否与-1
不同(如果等于-1
则表示文件结束)
所以没有FileInputStream
变成了int
您的 FileInputStream
是一个字节流。
当您调用 FileInputStream.read()
时,它 return 来自流的 byte
或 return -1 如果到达流的末尾。
当你写:c = in.read()) != -1
、
- a
byte
从流中读取,扩展为int
,分配回c
和 - 通过比较 returned 值与
-1
; 来检查一个字节是否被成功读取