【问题标题】:Problem writing on a .txt file using user input使用用户输入写入 .txt 文件时出现问题
【发布时间】:2021-06-01 07:12:43
【问题描述】:

我正在编写一个程序,它接受用户输入并将其显示在文本文件中。我无法将输入保存在文件中。其他类似的问题建议关闭 BufferedWriter,但是我使用的是 try-with-resource 块,据我所知,它应该自动关闭资源。当我使用 fileWriter.close();但是文本被保存,因为它正在关闭,它不会被重新打开,并且由于流被关闭而给我一个 IOException。我该如何解决这个问题?

主要方法

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;

public class TextReader {
    public static void main(String[] args) {
        Path path = Paths.get("/Users/Coding/Desktop/myFile.txt").toAbsolutePath();
        try (Scanner scan = new Scanner(System.in);
             BufferedWriter fileWriter = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {

            Reader reader = new Reader(scan, path, fileWriter);
            reader.menu();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

阅读器类

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Scanner;

public class Reader {

    Path path;
    Scanner scan;
    BufferedWriter fileWriter;

    Reader(Scanner scan, Path path, BufferedWriter fileWriter) {

        this.scan = scan;
        this.path = path;
        this.fileWriter = fileWriter;
    }

    public void menu() throws IOException {
        String task;

        do{
            System.out.print("What would you like to do today?: ");
            task = scan.nextLine();
            switch(task){
                case "1":
                    addData();
                    break;
                case "6":
                    System.out.println("Goodbye!");
                    System.exit(0);
                menu();
            }
        }while(!task.equals("6"));

    }

    void addData() throws IOException {
        boolean cont = false;
        do try {
            System.out.print("Enter Name of Player: ");
            String playerName = scan.nextLine();

            System.out.print("Enter Number of Games Played: ");
            int gamesPlayed = Integer.parseInt(scan.nextLine());

            System.out.print("Enter Number of Goals Made: ");
            int goals = Integer.parseInt(scan.nextLine());

            System.out.print("Enter Number of Assists Made: ");
            int assists = Integer.parseInt(scan.nextLine());

            System.out.print("Enter Number of Points Scored: ");
            int points = Integer.parseInt(scan.nextLine());

            System.out.print("Enter Number of Saves Made: ");
            int saves = Integer.parseInt(scan.nextLine());

            System.out.print("Enter Number of Shots Made: ");
            int shotsOnGoal = Integer.parseInt(scan.nextLine());

            fileWriter.write(
                    playerName + " " + gamesPlayed + " " + goals + " " +
                            assists + " " + points + " " + saves + " " + shotsOnGoal);
        } catch(NumberFormatException e){
            System.out.println("Enter Valid Input");
            cont = true;
//insert finally clause to close fileWriter here
        }while(cont);

    }
}

IF 如代码注释所示,在捕获到 NumberFormatException 后,fileWriter 在 finally 子句中关闭,显示以下异常

java.io.IOException: Stream closed
    at java.base/java.io.BufferedWriter.ensureOpen(BufferedWriter.java:107)
    at java.base/java.io.BufferedWriter.write(BufferedWriter.java:224)
    at java.base/java.io.Writer.write(Writer.java:249)
    at Reader.addData(Reader.java:74)
    at Reader.menu(Reader.java:28)
    at TextReader.main(TextReader.java:16)

【问题讨论】:

  • 从异常中添加堆栈跟踪。另请注意,如果任何输入错误,您永远不会将 cont 重新设置为 false(即它将保持无限循环,要求用户输入越来越多的玩家)。
  • 已添加异常,请参阅更新。请注意,行号可能与此处显示的代码不同,因为一些不相关的代码已被删除以保持问题的重点
  • 因此,您在此处发布的代码实际上不会导致异常,因为您忽略了 finally 块。为什么不发布所做的代码?另外:似乎addData 是关闭FileWriter 的错误位置。如果您想在main 中关闭它(如果您总是以打开它们的相同方法关闭资源,这是最简单的),或者在您完成编写后(即当用户选择退出时)可能在menu 中关闭它)。
  • 您正在关闭循环内的流,因此如果循环再次运行,您将尝试写入已关闭的流。您不应该将流从一种方法传递到另一种方法,然后关闭它。而是在需要的地方使用try with resources 打开流。

标签: java text-files nio


【解决方案1】:

主要

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;

public class TextReader {
    public static void main(String[] args) {
        Path path = Paths.get("/Users/Coding/Desktop/myFile.txt").toAbsolutePath();
        try (Scanner scan = new Scanner(System.in);
             BufferedWriter fileWriter = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {

            Reader reader = new Reader(scan, path, fileWriter);
            reader.menu();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

阅读器类

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Scanner;

public class Reader {

    Path path;
    Scanner scan;
    BufferedWriter fileWriter;


    Reader(Scanner scan, Path path, BufferedWriter fileWriter) {

        this.scan = scan;
        this.path = path;
        this.fileWriter = fileWriter;
    }

    public void menu() throws IOException {
        String task;

        do{
            System.out.print("What would you like to do today?: ");
            task = scan.nextLine();
            switch(task){
                case "1":
                    addData();
                    break;
                case "6":
                    System.out.println("Goodbye!");
                    System.exit(0);
                
            }
            fileWriter.close();
        }while(!task.equals("6"));

    }

    void addData() throws IOException {
        boolean cont = false;
        do try {
            System.out.print("Enter Name of Player: ");
            String playerName = scan.nextLine();

            System.out.print("Enter Number of Games Played: ");
            int gamesPlayed = Integer.parseInt(scan.nextLine());

            System.out.print("Enter Number of Goals Made: ");
            int goals = Integer.parseInt(scan.nextLine());

            System.out.print("Enter Number of Assists Made: ");
            int assists = Integer.parseInt(scan.nextLine());

            System.out.print("Enter Number of Points Scored: ");
            int points = Integer.parseInt(scan.nextLine());

            System.out.print("Enter Number of Saves Made: ");
            int saves = Integer.parseInt(scan.nextLine());

            System.out.print("Enter Number of Shots Made: ");
            int shotsOnGoal = Integer.parseInt(scan.nextLine());

            fileWriter.write(
                    playerName + " " + gamesPlayed + " " + goals + " " +
                            assists + " " + points + " " + saves + " " + shotsOnGoal);
            cont = false;
        } catch(NumberFormatException e){
            System.out.println("Enter Valid Input");
            cont = true;
        }while(cont);

    }
}


【讨论】:

  • 是的,有人告诉我,如果在这种情况下,我应该点击接受答案,但这需要我等待 2 天。
  • 考虑在您的答案中添加一些解释,解释代码的作用以及它如何解决问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-25
  • 2016-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多