英文:
How can I add new information to a .txt file without it removing any old data in java
问题
我想将所有销售记录存储在一个txt文件中,但每次输入新信息时都会删除旧信息。有任何想法为什么会这样吗?
try {
BufferedWriter bfw = new BufferedWriter(new FileWriter(file1));
BufferedWriter bfw1 = new BufferedWriter(new FileWriter(file2));
bfw.write(Total.getText());
bfw.newLine();
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date());
bfw1.write(timeStamp);
bfw1.newLine();
bfw.close();
bfw1.close();
} catch (IOException ex) {
Logger.getLogger(FrmFacturas.class.getName()).log(Level.SEVERE, null, ex);
}
英文:
I want to store all the sales in a txt file, but every time I enter new information it deletes the old information. Any idea why?
try {
BufferedWriter bfw = new BufferedWriter(new FileWriter(file1));
BufferedWriter bfw1 = new BufferedWriter(new FileWriter(file2));
bfw.write(Total.getText());
bfw.newLine();
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date());
bfw1.write(timeStamp);
bfw1.newLine();
bfw.close();
bfw1.close();
} catch (IOException ex) {
Logger.getLogger(FrmFacturas.class.getName()).log(Level.SEVERE, null, ex);
}
答案1
得分: 1
你可以在FileWriter构造函数中加入第二个参数:
BufferedWriter bfw = new BufferedWriter(new FileWriter(file1, true));
或者
你可以使用Files.nio:
Files.writeString(file1.toPath(), textToWrite, StandardOpenOption.APPEND)
英文:
You can put a second parameter to the FileWriter constructor:
BufferedWriter bfw = new BufferedWriter(new FileWriter(file1, true));
OR
you could use Files.nio:
Files.writeString(file1.toPath(), textToWrite, StandardOpenOption.APPEND)
答案2
得分: 0
你必须以追加模式打开文件,要做到这一点,在FileWriter中的第二个参数中添加true。
BufferedWriter bfw = new BufferedWriter(new FileWriter(file1, true));
英文:
You have to open the file in append mode to do this add true as the second parameter in FileWriter
BufferedWriter bfw = new BufferedWriter(new FileWriter(file1,true));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论