我正在学习java IO。在 read()
方法中,有一条通知表示
it returns -1 at the end of file
不知道这是什么意思? -1 位于文件末尾的重要性是什么
示例:
import java.io.*;
class Simple{
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("abc.txt");
int i;
while((i=fr.read())!=-1)
System.out.println((char)i);
fr.close();
}
}
最佳答案
请先查看文档!
https://docs.oracle.com/javase/7/docs/api/java/io/InputStreamReader.html#read()
相关部分:
public int read() throws IOException Reads a single character.
Overrides: read in class Reader
Returns: The character read, or -1 if the end of the stream has been reached
Throws: IOException - If an I/O error occurs
就其值(value)而言,这些通常被称为哨兵值。哨兵值用于通过明显无效响应的返回值来指示某些特殊条件(例如:-1,因为这显然不是字符)。将其视为状态或错误代码。在这种情况下,它意味着状态:文件结束。
关于java read方法在文件末尾返回-1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39476788/