如何在 Java 中编辑多个 .txt 文件

How do I edit multiple .txt files in Java

我正在尝试在 Java 中为学校创建一个 GradeManager class。我需要:

  1. 输入学生姓名

  2. 根据输入的姓名查找学生文件(我有 4 个学生)

  3. 编辑文件中的成绩

文件示例:John,123456789,10,8,7,87,91 (Name,ID,Q1,Q2,Q3,Midterm,Final) 并将编辑 Q1-Final

我不太明白如何将所有 4 个学生文件放入 editStuGrades() 而无需将它们全部放在一个文件中

这是我得到的:

public class GradeManager {
    private static Scanner command = new Scanner(System.in);

    public static void main(String[] args) throws Exception {
        System.out.println("Enter a students name: ");
        String commandInput = command.next();
        if (commandInput.equalsIgnoreCase("John")) {
            String filepath = FileSystems.getDefault().getPath("src", "Assignments", "John.txt").toAbsolutePath().toString();
            File inputFile = new File(filepath);
            Scanner line = new Scanner(inputFile);
            while (line.hasNext()) {
                String rLine = line.nextLine();
                String name = rLine.substring(0, rLine.indexOf(","));
                System.out.println("Name: " + name + " | ");
                editStuGrade();
            }

        }
        if (commandInput.equalsIgnoreCase("Matthew")) {
            String filepath = FileSystems.getDefault().getPath("src", "Assignments", "Matthew.txt").toAbsolutePath().toString();
            File inputFile = new File(filepath);
            Scanner line = new Scanner(inputFile);
            while (line.hasNext()) {
                String rLine = line.nextLine();
                String name = rLine.substring(0, rLine.indexOf(","));
                System.out.println("Name: " + name + " | " );
                editStuGrade();
            }

        }
    }
    public static void editStuGrade() {
        System.out.println("Would you like to edit or quit (edit | quit)?");
        String editInput = command.next();
        if (editInput.equalsIgnoreCase("edit")) {

        } else if (editInput.equalsIgnoreCase("quit")) {
            System.exit(0);
        }


    }
}

先看看 Passing Information to a Method or a Constructor

您想(尝试并做)的是使核心功能“通用”。面对现实吧,所有学生的学生数据读写基本相同,唯一的区别是源和目标。

为此,我将从一个 POJO(普通旧 Java 对象)开始,例如...

public class Student {

    private String name;
    private String id;
    private int q1Score;
    private int q2Score;
    private int q3Score;
    private int midTermScore;
    private int finalScore;

    public Student(String name, String id, int q1Score, int q2Score, int q3Score, int midTermScore, int finalScore) {
        this.name = name;
        this.id = id;
        this.q1Score = q1Score;
        this.q2Score = q2Score;
        this.q3Score = q3Score;
        this.midTermScore = midTermScore;
        this.finalScore = finalScore;
    }

    public static Student loadByName(String name) throws IOException {
        File file = new File(name + ".txt");
        if (!file.exists()) {
            throw new FileNotFoundException("No record exists for " + name);
        }

        try (Scanner input = new Scanner(file)) {
            input.useDelimiter(",");
            name = input.next();
            String id = input.next();
            int q1Score = input.nextInt();
            int q2Score = input.nextInt();
            int q3Score = input.nextInt();
            int midTermScore = input.nextInt();
            int finalScore = input.nextInt();

            return new Student(name, id, q1Score, q2Score, q3Score, midTermScore, finalScore);
        }
    }
    
    public void save() throws IOException {
        File file = new File(getName() + ".txt");
        StringJoiner joiner = new StringJoiner(",");
        joiner.add(getName());
        joiner.add(getId());
        joiner.add(Integer.toString(getQ1Score()));
        joiner.add(Integer.toString(getQ2Score()));
        joiner.add(Integer.toString(getQ3Score()));
        joiner.add(Integer.toString(getMidTermScore()));
        joiner.add(Integer.toString(getFinalScore()));
        
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
            bw.write(joiner.toString());
        }
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public int getQ1Score() {
        return q1Score;
    }

    public void setQ1Score(int q1Score) {
        this.q1Score = q1Score;
    }

    public int getQ2Score() {
        return q2Score;
    }

    public void setQ2Score(int q2Score) {
        this.q2Score = q2Score;
    }

    public int getQ3Score() {
        return q3Score;
    }

    public void setQ3Score(int q3Score) {
        this.q3Score = q3Score;
    }

    public int getMidTermScore() {
        return midTermScore;
    }

    public void setMidTermScore(int midTermScore) {
        this.midTermScore = midTermScore;
    }

    public int getFinalScore() {
        return finalScore;
    }

    public void setFinalScore(int finalScore) {
        this.finalScore = finalScore;
    }

}

nb:你可以只使用一个数组,但它的乐趣在哪里

所以,上面只是我们要管理的数据的一个容器。它提供了两种读取和写入学生信息的说服方法,因此我们不会“重复”代码并在此过程中引入可能的错误或维护问题(我们只有一个地方读取或写入数据)

接下来,任何需要与学生交互的方法都需要接受 Student POJO 的实例,例如...

protected void editStuGrade(Student student) throws IOException {
    //...
}

然后剩下的代码简单地归结为从用户那里获取信息并将其输入我们的工作流程...

public class Main {

    private Scanner command = new Scanner(System.in);

    public static void main(String[] args) throws Exception {
        new Main();
    }

    public Main() {
        System.out.println("Enter a students name: ");
        String commandInput = command.next();
        try {
            Student student = Student.loadByName(commandInput);
            editStuGrade(student);
        } catch (IOException ex) {
            System.out.println("Could not read student record: " + ex.getMessage());
        }
    }

    protected void editStuGrade(Student student) throws IOException {
        System.out.println("Would you like to edit or quit (edit | quit)?");
        String editInput = command.next();
        if (editInput.equalsIgnoreCase("edit")) {
            // Make some changes...
            student.save();
        } else if (editInput.equalsIgnoreCase("quit")) {
            System.exit(0);
        }

    }
}

可运行示例...

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.StringJoiner;

public class Main {

    private Scanner command = new Scanner(System.in);

    public static void main(String[] args) throws Exception {
        new Main();
    }

    public Main() {
        System.out.println("Enter a students name: ");
        String commandInput = command.next();
        try {
            Student student = Student.loadByName(commandInput);
            editStuGrade(student);
        } catch (IOException ex) {
            System.out.println("Could not read student record: " + ex.getMessage());
        }
    }

    protected void editStuGrade(Student student) throws IOException {
        System.out.println("Would you like to edit or quit (edit | quit)?");
        String editInput = command.next();
        if (editInput.equalsIgnoreCase("edit")) {
            // Make some changes...
            student.save();
        } else if (editInput.equalsIgnoreCase("quit")) {
            System.exit(0);
        }

    }

    public static class Student {

        private String name;
        private String id;
        private int q1Score;
        private int q2Score;
        private int q3Score;
        private int midTermScore;
        private int finalScore;

        public Student(String name, String id, int q1Score, int q2Score, int q3Score, int midTermScore, int finalScore) {
            this.name = name;
            this.id = id;
            this.q1Score = q1Score;
            this.q2Score = q2Score;
            this.q3Score = q3Score;
            this.midTermScore = midTermScore;
            this.finalScore = finalScore;
        }

        public static Student loadByName(String name) throws IOException {
            File file = new File(name + ".txt");
            if (!file.exists()) {
                throw new FileNotFoundException("No record exists for " + name);
            }

            try (Scanner input = new Scanner(file)) {
                input.useDelimiter(",");
                name = input.next();
                String id = input.next();
                int q1Score = input.nextInt();
                int q2Score = input.nextInt();
                int q3Score = input.nextInt();
                int midTermScore = input.nextInt();
                int finalScore = input.nextInt();

                return new Student(name, id, q1Score, q2Score, q3Score, midTermScore, finalScore);
            }
        }

        public void save() throws IOException {
            File file = new File(getName() + ".txt");
            StringJoiner joiner = new StringJoiner(",");
            joiner.add(getName());
            joiner.add(getId());
            joiner.add(Integer.toString(getQ1Score()));
            joiner.add(Integer.toString(getQ2Score()));
            joiner.add(Integer.toString(getQ3Score()));
            joiner.add(Integer.toString(getMidTermScore()));
            joiner.add(Integer.toString(getFinalScore()));

            try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
                bw.write(joiner.toString());
            }
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public int getQ1Score() {
            return q1Score;
        }

        public void setQ1Score(int q1Score) {
            this.q1Score = q1Score;
        }

        public int getQ2Score() {
            return q2Score;
        }

        public void setQ2Score(int q2Score) {
            this.q2Score = q2Score;
        }

        public int getQ3Score() {
            return q3Score;
        }

        public void setQ3Score(int q3Score) {
            this.q3Score = q3Score;
        }

        public int getMidTermScore() {
            return midTermScore;
        }

        public void setMidTermScore(int midTermScore) {
            this.midTermScore = midTermScore;
        }

        public int getFinalScore() {
            return finalScore;
        }

        public void setFinalScore(int finalScore) {
            this.finalScore = finalScore;
        }

    }
}