写入文件,输出文件在哪里?

2024-04-21

        FileWriter outFile = null;
        try {
            outFile = new FileWriter("member.txt");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
out.println("test");

运行该命令,member.txt 在哪里?我正在使用Windows Vista。启用了 UAC,因此当我运行它时,我认为它没有写入 txt 文件。然而,txt 文件已创建,但它是空的。


Java IO 中的相对路径是相对于当前工作目录的。在 Eclipse 中,这通常是项目根目录。您还写信给out代替outFile。这是一个小的重写:

    File file = new File("member.txt");
    FileWriter writer = null;
    try {
        writer = new FileWriter(file);
        writer.write("test");
    } catch (IOException e) {
        e.printStackTrace(); // I'd rather declare method with throws IOException and omit this catch.
    } finally {
        if (writer != null) try { writer.close(); } catch (IOException ignore) {}
    }
    System.out.printf("File is located at %s%n", file.getAbsolutePath());

关闭是强制性的,因为它将写入的数据刷新到文件中并释放文件锁。

不用说,在 Java IO 中使用相对路径是一种糟糕的做法。如果可以的话,最好使用类路径。ClassLoader#getResource(), getResourceAsStream()等等。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

写入文件,输出文件在哪里? 的相关文章

随机推荐