【问题标题】:Java - FileOutputStream overwrites file, but it doesn't seem to changeJava - FileOutputStream 覆盖文件,但它似乎没有改变
【发布时间】:2020-04-25 05:58:45
【问题描述】:

所以,当我使用FileOutputStream 写入文件时,它确实 更改了文件的内容,就像我使用InputStream 读取它时一样,我得到的正是我所写的。但是,当我在资源目录中打开文件时,它仍然和以前一样,尽管它被更改了。

我的代码:

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());
        }

    }
}

顺便说一句,我使用的是 IntelliJ IDEA,并且在资源文件夹中有这个文件。它只是一个.txt 文件,内容为Not changed,所以我可以知道它是否被覆盖。

我想知道这个问题是否与代码有关,如果是,我该如何解决?

【问题讨论】:

    标签: java file overwrite fileoutputstream


    【解决方案1】:

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

    【讨论】:

    • 刷新是什么意思?在 IDE 中还是在 Finder 中(我使用的是 MacOSX)?
    • 两个都试一下,我没用过IntelliJ,但是据我所知在eclipse中,有时候改内容后还是会看到旧文件,所以我用refresh(F5)来获取最新信息。您还可以尝试检查文件修改时间,以确保您正在写入正在检查的同一文件。
    • 我试过了,还是不行。使用 IntelliJ 的同步,我注意到运行程序后修改时间没有更新。
    • 可能是你从不同的路径访问,你可以像这样检查路径 - new File(Object.class.getResource(fileName).toURI()).getAbsolutePath()
    【解决方案2】:

    原来我不应该使用 Object.class.getResource(fileName) 从类路径打开文件,而是直接实例化一个 File 对象。

    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());
            }
        }
    }
    

    正如 CHN 所指出的,我认为这与路径有关。

    【讨论】:

      猜你喜欢
      • 2015-03-03
      • 1970-01-01
      • 2021-05-01
      • 2017-04-13
      • 1970-01-01
      • 2023-02-02
      • 2013-07-10
      • 2013-10-06
      • 1970-01-01
      相关资源
      最近更新 更多