我在这里写了一个代码来读取textFile的所有行,并且目前有一个结束程序的低效方法。我想阅读所选文本文件的每一行,直到文件中还没有任何内容还没有被读取,并将每行显示给用户。我已经搜索了各种方法,但大多数使用复杂的方法,我希望这是尽可能简单,没有任何先进的方法。一旦外部文本文件为空就停止BufferedReader JAVA
package textfilereader;
import java.io.*;
import java.util.Scanner;
import java.io.FileReader;
import java.io.IOException;
public class TextFileReader
{
public static void main(String[] args) throws IOException
{
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter the name of the text document you would like to open");
System.out.println("For example, 'userName.txt'");
String textFile = scanner.nextLine();
try (BufferedReader readFile = new BufferedReader (new FileReader("c:/Users/Nicholas/Desktop/"+textFile)))
{
System.out.println("Contents of the file: "+textFile);
for (int i = 0; i < 100; i++)
{
String line = readFile.readLine();
System.out.println(line);
if (line.equals(null))
{
i = 100;
//my inefficient method is currently to continue the loop
//if "i" is less than 100, this value can be any value
//if the line is a null it will set i to be 100 so the
//loop will stop
}
}
readFile.close();
}
}
}
'而((行= readFile.readLine()= NULL){...}' - 我强烈建议你看看[基本IO(HTTPS:/ /docs.oracle.com/javase/tutorial/essential/io/)和[BufferedReader#readLine的JavaDocs](https://docs.oracle.com/javase/8/docs/api/java/io/ BufferedReader.html#readLine--) – MadProgrammer
'while((line = readFile.readLine())!= null){..}' – davidxxx
得到一个错误消息,说“字符串不能转换为布尔值” –