我有filewriter
(显然)用于将用户信息写入文件;写得很好,程序运行正常,但是作者没有以所需的方式写入文件。我曾经注意到它写入的文件,它会留下空白行,有时我不想要它,我不明白为什么。下面是与文件编写相关的代码(它是文件中唯一使用filewriter
的位置)。所有变量等都已定义并正常工作。
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); // **note second param?**
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((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();
文件所需的输出是文件中任何地方都没有空白行,写入文件几次后对文件的实际输出如下所示:
答案 0 :(得分:2)
这段代码错了:
String CurrentData = "";
while((bufferedReader.readLine()) != null) {
line = CurrentData;
bw.write(CurrentData);
((BufferedWriter) bw).newLine();
}
CurrentData
(顺便说一句,变量应该以小写字母开头)总是""
(空字符串),所以你什么都不写,然后是新的行字符。
while((currentData=bufferedReader.readLine()) != null) {...}
应该有效