外部文本文件为空后停止 BufferedReader JAVA
Stopping a BufferedReader once the external text file is empty 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();
}
}
}
您应该使用 while
循环而不是 for
循环。
一个例子
// ...
String line = null;
while ((line = readFile.readLine()) != null) {
System.out.println(line);
}
readFile.close();
// ...
我在这里写了一个代码来读取一个文本文件的所有行,目前有一个低效的结束程序的方法。我想读取所选文本文件的每一行,直到文件中没有任何内容尚未读取,然后将每一行显示给用户。我搜索了各种方法,但大多数使用复杂的方法,我希望它尽可能简单,没有任何高级方法。
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();
}
}
}
您应该使用 while
循环而不是 for
循环。
一个例子
// ...
String line = null;
while ((line = readFile.readLine()) != null) {
System.out.println(line);
}
readFile.close();
// ...