简体   繁体   中英

Java - FileOutputStream overwrites file, but it doesn't seem to change

So, when I write to a file using FileOutputStream , it does change the file's contents, seen as when I read it with an InputStream I get exactly what I wrote. However, when I open the file in the resources directory, it remains the same as before, despite it being changed.

My code:

import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;

public class Program {

    public static void main(String[] args) throws URISyntaxException, IOException {
        String edit = "Edit2";
        String fileName = "/File.txt";
        URL url = Object.class.getResource(fileName);

        try (FileOutputStream fos = new FileOutputStream(new File(url.toURI()))) {
            fos.write(edit.getBytes());
        }

        try(InputStream is = Object.class.getResourceAsStream(fileName)) {
            StringBuilder sb = new StringBuilder();
            int read = is.read();
            while (read != -1) {
                sb.append((char) read);
                read = is.read();
            }
            System.out.println(sb.toString());
        }

    }
}

By the way, I am using IntelliJ IDEA, and have this file on the resources folder. It's just a .txt file with contents Not changed , so I can know if it was overwritten.

I would want to know whether this problem is related to code or not, and if it is, how can I fix it?

听起来很傻,但在打开文件之前尝试刷新文件夹。

Turns out that I shouldn't be using Object.class.getResource(fileName) to open the file from the classpath, but instead directly instantiating a File object.

import java.io.*;

public class Program {
    public static void main(String[] args) throws IOException {
        String edit = "Edit";
        String fileName = "resources/File.txt";
        File file = new File(fileName);

        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(edit.getBytes());
        }

        try (InputStream is = new FileInputStream(file)) {
            StringBuilder sb = new StringBuilder();
            int read = is.read();
            while (read != -1) {
                sb.append((char) read);
                read = is.read();
            }
            System.out.println(sb.toString());
        }
    }
}

I believed it's related to the path, as CHN pointed out.

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