我试图提示用户在文件末尾附加文本或覆盖文件;但是当他们选择附加选项时,它仍然会覆盖。知道为什么吗?
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();
答案 0 :(得分:4)
等到这个时候:
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'));