[英]Write and read txt file
我正在嘗試做包含患者信息的項目,並在用戶需要時打印它們。 但它目前只增加了一個人。 我想添加無限的信息,但我不知道如何修復它。
public static void saveChanges(ArrayList<Human> humans) throws IOException {
File veritabani = new File("patients.txt");
System.gc();
RandomAccessFile raf = new RandomAccessFile(veritabani, "rw");
raf.close();
veritabani.delete();
int ctrWhile = 0;
for (int yazdir = 0; yazdir < humans.size(); yazdir++) {
File f = new File("patients.txt");
PrintWriter pw = new PrintWriter(new FileOutputStream(f, true));
String tName=humans.get(yazdir).getNameAndSurname();
int tID=humans.get(yazdir).getTC();
int tAge=humans.get(yazdir).getAge();
boolean tInsuance=humans.get(yazdir).isInsurance();
String tComplain=humans.get(yazdir).getComplain();
if (ctrWhile== 0) {
pw.append(tName+"-"+tID+"-"+tAge+"-"+"-"+tInsuance+"-"+tComplain+"-");
ctrWhile++;
} else {
pw.append("\n"+tName+"-"+tID+"-"+tAge+"-"+"-"+tInsuance+"-"+tComplain+"-");
}
pw.close();
}
}
每次循環時,您似乎都在創建一個新文件,寫入並關閉它。 因此,每次通過循環時,您都會覆蓋之前創建的文件。
在進入循環之前創建文件,並在完成循環后關閉它; 只在循環中寫入它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.