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

标签 java

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

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 的初始化,直到您真正需要它为止。

您还可以通过删除 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'));

关于java - 使用 PrintWriter 和 if 语句追加与覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52839309/

相关文章:

java - 为什么我会收到 "createCriteria is not valid without active transaction"异常?

java - 跨域认证

java - 获取页面信息时出现 NullPointerException

java - 安卓;从动态文本字段适配器中获取文本

用于匹配文件中的十六进制数字的 Java 正则表达式

java - 使用java泛型添加2种类型的参数

java - 如何为 Google Java 风格设置 emacs

java - 如何解析bazel中的java_toolchain

java - 如何在 MigLayout 中用背景颜色填充跨越区域?

java - 如何在selenium java中通过断言验证动态表