【发布时间】:2018-02-22 02:03:57
【问题描述】:
我目前正在做一个测试项目,以了解如何读取/写入文本文件。这是我的代码:
package testings;
import java.util.Scanner;
import java.io.*;
public class Writing_Reading_files {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
File testFile = new File("testFile.dat");
String test, sName;
try{
PrintWriter print = new PrintWriter(new BufferedWriter(new FileWriter(testFile)));
test = in.nextLine();
print.println(test);
print.close();
}catch(IOException e) {
System.out.println("IO exception");
System.exit(0);
}
try {
BufferedReader readerName = new BufferedReader(new FileReader(testFile));
while(readerName != null) {
sName = readerName.readLine();
System.out.println(sName);
}
readerName.close();
} catch(FileNotFoundException e) {
System.out.println("FileNotFound");
System.exit(0);
} catch(IOException e) {
System.out.println("IO exception");
System.exit(0);
}
}
}
如果我尝试 while(readerName.readLine != null),while 循环会导致吐出我放置的行,然后为无限循环返回 null,它会停止无限循环,但只输出 null,我不知道在哪里从那里开始,我尝试遵循 youtube 教程,但他的代码与我的代码相同,所以我不确定为什么我是 null 不断重复。提前感谢您的帮助。
【问题讨论】:
标签: java while-loop bufferedreader