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

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'));

10-07 16:31