开发者

Writing to a file, where is the output file?

        FileWriter outFile = null;
        try {
            outFile = new FileWriter("member.txt");
        } catch (IOException e) {
            // TODO Au开发者_JS百科to-generated catch block
            e.printStackTrace();
        }
out.println("test");

Running that command, where is the member.txt ? I am using windows vista. UAC enabled so when I run it, I don't think it's writing to the txt file. txt file is created however, but it's empty.


Relative paths in Java IO are relative to current working directory. In Eclipse, that's usually the project root. You're also writing to out instead of outFile. Here's a minor rewrite:

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

Closing is mandatory since it flushes the written data into the file and releases the file lock.

Needless to say that it's a poor practice to use relative paths in Java IO. If you can, rather make use of the classpath. ClassLoader#getResource(), getResourceAsStream() and so on.


If the file is successfully created (no exception is raised), it is in the current working directory.


For the Java class you're executing, right click on the file and go to "Run As -> Run Configurations..."

In this screen, go to the "Arguments" tab. At the bottom of the screen, look for the "Working directory" setting. This is the directory that your Java class will run from.

In your example, you're creating "member.txt" in the current directory, so it will show up in whatever location your "Working directory" is set to.


It depends on the IDE you're using also. It will usually go into the same directory that the file.java is located at. I think programs like Eclipse and Netbeans may toss it in a different directory.


If running from Eclipse, the current working directory will be your project's base directory (view your project properties to find that location on disk). You should be able to see the file in the Project Explorer by refreshing the project (click on the project and hit F5).

You can specify an alternative working directory from the Run Configurations dialog under the Arguments tab.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜