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

KJW*_*KJW 3 java eclipse file-io

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

运行该命令,member.txt在哪里?我正在使用Windows vista.UAC启用所以当我运行它时,我不认为它正在写入txt文件.但是创建了txt文件,但它是空的.

Bal*_*usC 6

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());
Run Code Online (Sandbox Code Playgroud)

关闭是必需的,因为它将写入的数据刷新到文件中并释放文件锁.

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