我试图提示用户将文本附加到文件末尾或覆盖文件;但当他们选择追加选项时,它仍然会覆盖。知道为什么吗?
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();
最佳答案
当你到达这个区 block 时:
else if (appendChar == 'Y') {
outputFile = new PrintWriter(fileWrite);
}
您已经在此语句中初始化了outputFile
:
PrintWriter outputFile = new PrintWriter(fileName);
并且 PrintWriter(String filename)
构造函数已截断文件。所以现在追加它已经太晚了。
您需要做的是不使用任何特定值初始化outputFile
;只需声明即可。您稍后将其设置为适当的值。另外,您应该延迟 fileWrite
的初始化,直到您真正需要它为止。
您还可以通过删除 outputFile
和 fileWrite
的声明并替换以下所有行来使代码更加简洁:
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'));
关于java - 使用 PrintWriter 和 if 语句追加与覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52839309/