我有一个任务要做考试模拟器。我的意思是,在老师在某些科目中输入分数后,学生输入名字,姓氏和出生,然后他决定学生是否通过科目。所以,我有一个问题,如何用换行符写入文件文本并通过重写此文件来读取(逐行读取并重写)。例如:我在文件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
这就是我的方法。我有一个问题原因,重写后我没有换行符,如果添加新用户,则此方法只是删除旧信息,然后添加新信息。有什么问题?请帮我。
这是学生添加信息的一种方法(此方法具有学生班级)。
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();
}
}
答案 0 :(得分:1)
编辑代码
try(BufferedWriter writer = new BufferedWriter(new FileWriter("test.txt")))
到
try(BufferedWriter writer = new BufferedWriter(new FileWriter("test.txt", true)))
这将启用附加模式,而不是覆盖旧数据。