我有BufferedWriter
用于向用户详细信息写入文件。我注意到,它不是以我想要的格式写入文件,我似乎无法找到一种方法,它允许我在新行上写文本,而不会写出已存在的内容或复制文件中已有的文本。有什么办法可以编辑下面的代码,允许它进入上面的代码吗?
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);
FileOutputStream fos = new FileOutputStream(file, true);
Writer bw = new BufferedWriter(new OutputStreamWriter(fos, "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((currentData=bufferedReader.readLine()) != null) {
line = currentData;
bw.write(currentData);
((BufferedWriter) bw).newLine();
}
bw.write(Details);
System.out.println("Account created!");
程序没有问题(所有variables
都正常工作并且已在某处声明)我只发布了与问题相关的代码片段。运行几次后,文件的当前输出看起来像this
答案 0 :(得分:0)
我知道了!变化:
while((currentData=bufferedReader.readLine()) != null) {
line = currentData;
bw.write(currentData);
((BufferedWriter) bw).newLine();
}
bw.write(Details);
为:
bw.append(Details);
((BufferedWriter) bw).newLine();
这确保了不会写入两次数据,除了从用户获得的信息之外,它不会复制任何文本。