当 read() 方法在 java 中到达文件末尾时会返回什么值?
输入流类的read()方法逐字节读取给定文件的内容,并以整数形式返回读取字节的 ASCII 值。在读取文件时,如果它到达文件末尾,则此方法将返回 -1。
示例
假设我们在当前目录中有一个文本文件 (sample.txt),其中有简单的文本“Hello welcome”。以下 Java 程序使用 read() 方法逐字节地读取文件内容,并打印为每个字节返回的整数值。
由于我们没有检查文件末尾,因此 read() 方法到达末尾,输出的最后一个整数将为 -1。
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class EndOfFileExample {
public static void main(String[] args) {
try{
File file = new File("sample.txt");
DataInputStream inputStream = new DataInputStream(new FileInputStream(file));
System.out.println(file.length());
for(int i=0; i<=file.length();i++) {
int num = inputStream.read();
System.out.println(num);
}
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}输出
13 72 101 108 108 111 32 119 101 108 99 111 109 101 -1
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP