【问题标题】:Read a single line from text file & not the entire file (using buffered reader)从文本文件中读取一行而不是整个文件(使用 bufferedreader)
【发布时间】:2023-12-19 15:57:02
【问题描述】:

我正在尝试编写一段代码,该代码使用缓冲阅读器从 java 中的文本文件中读取单行文本。例如,代码会从文本文件中输出单行,然后你输入它所说的内容,然后它会输出下一行,依此类推。

到目前为止我的代码:

public class JavaApplication6 {

    public static String scannedrap;
    public static String scannedrapper;

    public static void main(String[] args) throws FileNotFoundException, IOException {
        File Tunes;
        Tunes = new File("E:\\NEA/90sTunes.txt");

        System.out.println("Ready? Y/N");
        Scanner SnD;
        SnD = new Scanner(System.in);
        String QnA = SnD.nextLine();

        if (QnA.equals("y") || QnA.equals("Y")) {

            System.out.println("ok, starting game...\n");
            try {

                File f = new File("E:\\NEA/90sTunes.txt");

                BufferedReader b = new BufferedReader(new FileReader(f));

                String readLine = "";

                while ((readLine = b.readLine()) != null) {
                    System.out.println(readLine);
                }

            } catch (IOException e) {
            }
        }
    }
}

它输出:

Ready? Y/N
y
ok, starting game...
(and then the whole text file)

但我希望实现这样的目标:

Ready? Y/N 
y
ok, starting game...
(first line of file outputted)
please enter (the line outputted)

& 然后重复此操作,遍历文本文件中的每一行,直到到达文本文件的末尾(它会输出类似“游戏完成”的内容)...

【问题讨论】:

  • 您在顶部的File Tunes; Tunes = ... 行是多余的
  • 这也是非常糟糕的做法,尤其是在学习编码时,编写空的 catch 块。如果你要写一个空的catch,你最好不要尝试catch。 (在未来的某个时候,您很可能会发布一个 q 说“我的程序运行但不执行任何操作并退出” - 因为它正在命中 s 文件未找到但您默默地丢弃了错误消息。省去头痛,总是做点什么有一个例外)
  • @Cyber​​Dev :您需要在 System.out.println(readLine); 之后的 while(){ ... } 循环内使用扫描仪;

标签: java file java.util.scanner bufferedreader filereader


【解决方案1】:

这将读取第一行“.get(0)”。

String line0 = Files.readAllLines(Paths.get("enter_file_name.txt")).get(0);

【讨论】:

    【解决方案2】:

    这段代码逐行读取整个文件,不会停下来询问用户输入:

            while ((readLine = b.readLine()) != null) {
                System.out.println(readLine);
            }
    

    考虑在循环体中添加一条语句来寻求用户的一些输入,就像您在上面询问它们是否准备好时所做的那样(您只需要在循环中添加一行代码,例如分配值的行到 QnA )

    【讨论】:

      最近更新 更多