gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:36:28 25 4
gpt4 key购买 nike

        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()等。

关于java - 写入文件,输出文件在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3515745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com