【问题标题】:Buffered reader causing an infinite loop缓冲读取器导致无限循环
【发布时间】: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


    【解决方案1】:

    为什么readerName 会变成null?也许你的意思是readLine返回的Stringnull

    考虑

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

    还可以考虑在打开文件时使用try-with-resources

    【讨论】:

    • 我尝试了资源、相同的输出和 sName,它有点帮助,输出变成了我的输入,然后只有一个 null
    • @NathanGentle 不使用此代码。它永远不会打印空值。 “输出变成了我的输入”毫无意义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-16
    • 1970-01-01
    • 2013-07-06
    • 2017-05-02
    • 2020-08-27
    • 2021-05-07
    相关资源
    最近更新 更多