2
我不確定爲什麼下面的代碼會導致Java每次都會覆蓋已存在於我的文件中的數據,而當我想要的是實際上將每條新數據寫入新行時。我已經包含了相關的代碼片斷(我知道你可能認爲變量中有錯誤,但是沒有,程序工作正常)。有人可以幫助我理解是什麼導致了這種情況,是我使用文件編寫器的方式嗎?這段代碼爲什麼會導致Java寫入文件中的數據?
String DirToWriteFile = System.getProperty("user.dir") + "/VirtualATM.txt"; //Get path to write text file to.
String Details = "Name: " + name + " CardNo: " + CardNo + " Current Balance: " + balance + " overdraft? " + OverDraft + " OverDraftLimit: " + OverDraftLimit + " pin: " + PinToWrite;
try{
//Create writer to write to files.
File file = new File(DirToWriteFile);
Writer bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader("VirtualATM.txt");
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
String CurrentData = "";
while((bufferedReader.readLine()) != null) {
line = CurrentData;
bw.write(CurrentData);
((BufferedWriter) bw).newLine();
}
bw.write(Details);
System.out.println("Account created!");
System.out.println(name + " Your card number is: " + CardNo);
// close the reader.
bufferedReader.close();
//Close the writer.
bw.close();