简体   繁体   English

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

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

I'm using Java, and I have a method that replaces a value of a parameter in configFile .我使用的是 Java,我有一个方法可以替换configFile中的参数值。 I use try-with-resources so that both will be closed automatically.我使用 try-with-resources 这样两者都会自动关闭。 However, I encounter an unexpected behavior - the while loop doesn't read anything from that file because immediately after Java enters the try-with-resources block, configFile becomes empty.但是,我遇到了一个意想不到的行为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 I change to code to be like this below, it works as expected.如果我将代码更改为如下所示,它会按预期工作。

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

I don't understand what causes configFile to become empty.我不明白是什么导致configFile变空。 Can someone explain what's wrong?有人可以解释什么是错的吗?

The FileWriter(String fileName) constructor calls FileOutputStream(String name) which sets the append flag to false. FileWriter(String fileName)构造函数调用FileOutputStream(String name) ,它将append标志设置为 false。 This means the file will not be opened in append mode.这意味着该文件将不会以 append 模式打开。
Based on my testing on windows the file is immediately cleared if the append flag is not set.根据我对 windows 的测试,如果未设置 append 标志,该文件会立即被清除。 So in your first variant there's nothing to read, since it was cleared.因此,在您的第一个变体中,没有什么可读的,因为它已被清除。 Your second variant works as it's cleared after you've read the content into your StringBuffer .在您将内容读入StringBuffer后,您的第二个变体会被清除。

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

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