Writing to a file, where is the output file?

        FileWriter outFile = null;
        try {
            outFile = new FileWriter("member.txt");
        } catch (IOException e) {
            // TODO Auto-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.

Answer

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.

Leave a Reply

Your email address will not be published. Required fields are marked *