追加与覆盖使用PrintWriter和if语句



我试图提示用户将文本附加到文件末尾或覆盖文件;但是当他们选择附加选项时,它仍然会覆盖。知道为什么吗?

String fileName = JOptionPane.showInputDialog("Enter file name: ");
String appendStr;
char appendChar;
PrintWriter outputFile = new PrintWriter(fileName);
FileWriter fileWrite = new FileWriter(fileName, true);
do {
appendStr = JOptionPane.showInputDialog("Would you like to append to the end of this file? (Y/N) " +
"[File will be over written if you choose not to append.]");
appendChar = appendStr.charAt(0);
} while (appendChar != 'Y' && appendChar != 'N');
if (appendChar == 'N') {
// Create PritnWriter object and pass file name names.txt
outputFile = new PrintWriter(fileName);
}
else if (appendChar == 'Y') {
outputFile = new PrintWriter(fileWrite);
}
// Prompt for number of names to be input * init count control var
String namesCountString = JOptionPane.showInputDialog("Number of names to be written to file: ");
int namesCountInt = Integer.parseInt(namesCountString);
// Prompt user for names & write to file
do {
String inputName = JOptionPane.showInputDialog("Input a name to write to file: ");
outputFile.println(inputName);
// Decrement count control var
namesCountInt--;
} while (namesCountInt > 0);
// Close file
outputFile.close();

当你到达这个块时:

else if (appendChar == 'Y') {
outputFile = new PrintWriter(fileWrite);
}

您已经初始化了此语句中的outputFile

PrintWriter outputFile = new PrintWriter(fileName);

并且PrintWriter(String filename)构造函数截断了该文件。所以现在附加为时已晚。

你需要做的不是用任何特定的值初始化outputFile;只需声明它。稍后会将其设置为适当的值。此外,您应该延迟fileWrite的初始化,直到您实际需要它。

还可以通过删除outputFilefileWrite的声明并替换以下所有行来使代码更加简洁:

if (appendChar == 'N') {
//Create PritnWriter object and pass file name names.txt
outputFile = new PrintWriter(fileName);
}
else if (appendChar == 'Y') {
outputFile = new PrintWriter(fileWrite);
}

用这一行:

PrintWriter outputFile = new PrintWriter(new FileWriter(fileName, appendChar == 'Y'));

最新更新