gpt4 book ai didi

Java 读/写文件

转载 作者:行者123 更新时间:2023-12-02 10:44:00 29 4
gpt4 key购买 nike

我有一个任务是制作考试模拟器。我的意思是,在老师输入某些科目的分数后,学生输入他的名字、姓氏和出生,然后他决定学生是否通过科目。所以,我有一个问题,如何用新行写入文件文本并通过重写该文件来读取(逐行读取并重写)。例如:我在文件 Jimmy Kordon 05.10.1998 中添加这样的文本,如何为此创建新行,我的意思是在 1998 之后,然后添加另一个笔划。它应该看起来像这样:

Jimmy Kordon 05.10.1998
Alex Starr 12.09.2000

在此之后,我调用另一个方法来重写此内容

Jimmy Kordon 05.10.1998 200.0 yes
Alex Starr 12.09.2000 10.0 no

我就是这样做的。我有一个问题,因为重写后我没有换行符,如果添加新人,此方法只需删除旧信息,然后添加新信息。有什么问题?请帮我。

这是学生添加信息的方法(该方法有学生类(class))。

public void write() throws IOException {
Scanner in = new Scanner(System.in);
System.out.println("Input name");
String name = in.nextLine();
setName(name);

System.out.println("Input last name");
String lastName = in.nextLine();
setLastName(lastName);

System.out.println("Input birthday");
String birth = in.nextLine();
setBirth(birth);

String ex = getName() + " " + getLastName() + " " + getBirth();

BufferedWriter writer = new BufferedWriter(new FileWriter("test.txt"));
try {
writer.write(getName() + " " + getLastName() + " " + getBirth());
writer.newLine();
//writer.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
writer.close();
}
}

这是我从教师类里面调用的方法来重写此信息:

private void inputMarks() {
Scanner in = new Scanner(System.in);

System.out.println("Input Math mark");
emM = new ExamMarks();
emM.setMath(in.nextDouble());

System.out.println("Input Physics mark");
emP = new ExamMarks();
emP.setPhysics(in.nextDouble());

System.out.println("Input Ukrainian mark");
emU = new ExamMarks();
emU.setUkrainian(in.nextDouble());

System.out.println("Input English mark");
emE = new ExamMarks();
emE.setEnglish(in.nextDouble());

}

private double Arithm(double Math, double Physics, double Ukrainian, double English) {
double sum = Math + Physics + Ukrainian + English;
double average = sum / 4.0;
return average;
}

public void rewrite() {
inputMarks();

String a = read();

System.out.println(Arithm(emM.getMath(), emP.getPhysics(), emU.getUkrainian(), emE.getEnglish()));

Scanner in = new Scanner(System.in);
System.out.println("Input yes/no");
String YesNo = in.nextLine();

try(BufferedWriter writer = new BufferedWriter(new FileWriter("test.txt"))) {
writer.write(a + " " + Arithm(emM.getMath(), emP.getPhysics(), emU.getUkrainian(), emE.getEnglish())
+ " " + YesNo);
writer.newLine();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}

最佳答案

编辑代码

try(BufferedWriter writer = new BufferedWriter(new FileWriter("test.txt")))

try(BufferedWriter writer = new BufferedWriter(new FileWriter("test.txt", true)))

这将启用附加模式而不是覆盖旧数据。

关于Java 读/写文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52725980/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com