我是 Java 新手,正在学习如何从 .txt 读取文件。我在讲座中偶然发现了许多笔记,我只是想知道当我尝试从我的小而简单的 java 代码中读取文件时为什么必须是 while(t!=-1) 。
感谢您的回答。 :)
编辑:谢谢你们的回答。我知道-1意味着文件结束,因此循环将继续,直到文件被完全读取。但它必须是-1吗?这是Java中的某种特定规则吗?谢谢。
import java.io.*;
public class test2 {
public static void main(String[] args) throws Exception{
FileReader inone = new FileReader("myfile.txt");
int t=inone.read();
while (t!=-1) {
System.out.print((char)t);
t=inone.read();
}
}
}
最佳答案
我猜你正在谈论读取文件内容的循环。
通常看起来像:
while (int symbol = inputStreamRef.read()!=-1) {
// do something
}
inputStreamRef
是 InputStream子类对象。
inputStreamRef.read()
- 读取文件,并在到达文件末尾时返回-1
。
while (symbol != -1)
表示尚未到达文件末尾,我们需要继续读取文件内容。
根据您发布的代码,查看我的评论:
// you are initializing the reader for the file
FileReader inone = new FileReader("myfile.txt");
// reading the first byte to the 't' variable
int t=inone.read();
// if file is empty, 't' will contain -1
// and loop won't start
while (t!=-1) {
// if t does not contain -1, then end of file is not reached
// printing byte
System.out.print((char)t);
// reading the next byte
t=inone.read();
}
关于java - 我是 Java 新手, while(t!=-1) [READFILE] 意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36712176/