简体   繁体   English

使用用户输入在 a.txt 文件上写入问题

[英]Problem writing on a .txt file using user input

I am writing a program that takes user input and displays it in a text file.我正在编写一个接受用户输入并将其显示在文本文件中的程序。 I am having trouble having the input save on the file.我无法将输入保存在文件中。 Other similar questions have suggested to close the BufferedWriter, however I'm using a try-with-resource block which, as I understand it, should auto-close the resource.其他类似的问题建议关闭 BufferedWriter,但是我使用的是 try-with-resource 块,据我所知,它应该自动关闭资源。 When I use fileWriter.close();当我使用 fileWriter.close(); the text is saved however because it is being closed it will not be re-opened and I am given an IOException due to the stream being closed.但是文本已保存,因为它正在关闭,因此不会重新打开,并且由于 stream 已关闭,我会收到 IOException。 How could I fix this issue?我该如何解决这个问题?

Main Method主要方法

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();
        }
    }
}

Reader Class阅读器 Class

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 fileWriter is closed in a finally clause after catching the NumberFormatException as indicated in the comment of the code, the following Exception is displayed IF fileWriter 在捕获 NumberFormatException 后在 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)

Main主要的

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();
        }

    }
}

Reader Class阅读器 Class

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);

    }
}


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM