简体   繁体   中英

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 . I use try-with-resources so that both will be closed automatically. 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.

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. Can someone explain what's wrong?

The FileWriter(String fileName) constructor calls FileOutputStream(String name) which sets the append flag to false. This means the file will not be opened in append mode.
Based on my testing on windows the file is immediately cleared if the append flag is not set. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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