[英]Java Read/Write File
我的任務是制作考試模擬器。 我的意思是,在老師在某些科目中輸入分數后,學生輸入名字,姓氏和出生,然后他決定學生是否通過科目。 所以,我有一個問題,如何用換行符寫入文件文本並通過重寫此文件來讀取(逐行讀取並重寫)。 例如:我在文件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();
}
}
編輯代碼
try(BufferedWriter writer = new BufferedWriter(new FileWriter("test.txt")))
至
try(BufferedWriter writer = new BufferedWriter(new FileWriter("test.txt", true)))
這將啟用附加模式,而不是覆蓋舊數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.