我正在使用带有JFrameForm的netbeans制作储蓄计算器。下面是我保存为.txt的工作代码。出于某种原因,当我点击保存时,它不会附加到新行,也不会保存。我想然后将某些行加载到数组并显示在我的文本区域中。例如储蓄领域。保存按钮的第一个代码,加载按钮的第二个块。
BufferedWriter writer = null;
try{
writer = new BufferedWriter(new FileWriter("C:\\test.txt"));
writer.write("\n" + date + "\t" + gross + "\t" + tax + "\t" + savings);
}
catch (Exception e){
JOptionPane.showMessageDialog(null, "Error saving");
}finally{
try{
//close the writer
writer.close();
}catch (Exception e){
JOptionPane.showMessageDialog(null, "Error closing save");
}
}
try{
FileReader reader = new FileReader("C:\\test.txt");
BufferedReader br = new BufferedReader(reader);
txaMain.read(br, null);
br.close();
}
catch(Exception E){
JOptionPane.showMessageDialog(null, "Error opening file");
}
答案 0 :(得分:1)
for some reason when I click save it will not append to a new line and wont save at all
它没有保存,因为你没有刷新从write方法中获取的字符缓冲区流。
<强>溶液强>
从文本文件写完后, flush
writer = new BufferedWriter(new FileWriter("C:\\test.txt"));
writer.write("\n" + date + "\t" + gross + "\t" + tax + "\t" + savings);
writer.flush();
此外,如果您想在保存文字时附加到该文件,请在FileWriter
FileWriter("C:\\test.txt, true")
true 中添加一个参数,以便在撰写时附加该文件。< / p>
public FileWriter(String fileName,
boolean append)