缓冲读卡器导致无限循环

时间:2018-02-22 02:03:57

标签: java while-loop bufferedreader

我目前正在做一个测试项目,以了解如何读/写文本文件。这是我的代码:

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循环导致吐出我放入的行然后为无限循环的空值如果我尝试While(readerName.readLine!= null)它停止无限循环但只输出null并且我不知道从那里开始,我已经尝试过关注youtube教程,但他的代码与我的代码相同,所以我不确定为什么我的null会不断重复。提前感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

为什么readerName会成为null?也许您的意思是String返回的readLinenull

考虑

BufferedReader readerName = new BufferedReader(new FileReader(testFile));
String sName = readerName.readLine();
while(sName != null) {
    System.out.println(sName);
    sName = readerName.readLine();
}

打开文件时也请考虑使用try-with-resources

相关问题