繁体   English   中英

使用相同的 try-with-resources 读取和写入文件

[英]Reading and writing to the file using same try-with-resources

我使用的是 Java,我有一个方法可以替换configFile中的参数值。 我使用 try-with-resources 这样两者都会自动关闭。 但是,我遇到了一个意想不到的行为while循环没有从该文件中读取任何内容,因为在 Java 进入 try-with-resources 块后, configFile立即变为空。

private static boolean replaceValue(String param, String newValue) throws IOException {
    try (BufferedReader br = new BufferedReader(new FileReader(configFile));
         BufferedWriter bw = new BufferedWriter(new FileWriter(configFile))) {
        String line;
        StringBuilder sb = new StringBuilder();
        boolean isParamPresent = false;
        while ((line = br.readLine()) != null) {
            if (line.startsWith(param + configDelimiter)) {
                line = line.replaceAll("(?<==).*", newValue);
                isParamPresent = true;
            }
            sb.append(line);
            sb.append("\n");
        }
        if (isParamPresent) {
            bw.write(sb.toString());
            return true;
        }
    }
    return false;
}

如果我将代码更改为如下所示,它会按预期工作。

            if (isParamPresent) {
            try (BufferedWriter bw = new BufferedWriter(new FileWriter(configFile))) {
                bw.write(sb.toString());
                return true;
            }

我不明白是什么导致configFile变空。 有人可以解释什么是错的吗?

FileWriter(String fileName)构造函数调用FileOutputStream(String name) ,它将append标志设置为 false。 这意味着该文件将不会以 append 模式打开。
根据我对 windows 的测试,如果未设置 append 标志,该文件会立即被清除。 因此,在您的第一个变体中,没有什么可读的,因为它已被清除。 在您将内容读入StringBuffer后,您的第二个变体会被清除。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM