gpt4 book ai didi

java - 为什么我的文件写入器在写入文件时会留下不必要的行?

转载 作者:行者123 更新时间:2023-12-02 05:25:11 24 4
gpt4 key购买 nike

我有一个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();

文件所需的输出是文件中任何地方都没有空行的地方,写入几次后文件的实际输出如下所示:

output the the file

最佳答案

这段代码是错误的:

String CurrentData = "";
while((bufferedReader.readLine()) != null) {
line = CurrentData;
bw.write(CurrentData);
((BufferedWriter) bw).newLine();
}

CurrentData(顺便说一句,变量应以小写字母开头)始终为 "" (空字符串),因此您什么也不写,然后是一个新行字符。

while((currentData=bufferedReader.readLine()) != null) {...}

应该可以

关于java - 为什么我的文件写入器在写入文件时会留下不必要的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26123594/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com