Using the FileWriter with a full path

chris yo picture chris yo · Jul 18, 2013 · Viewed 19.9k times · Source

I specified the full path of the file location when I created a FileWriter, but I did not see the file being created. I also did not get any error during file creation.

Here's a snippet of my code:

public void writeToFile(String fullpath, String contents) {
    File file = new File(fullpath, "contents.txt");
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    try {
        BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile()));
        bw.write(contents);
        bw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

fullpath is "D:/codes/sources/logs/../../bin/logs". I have searched my whole directory, but I cannot find the file anywhere. If I specify just the filename only [File file = new File("contents.txt");] , it is able to save the contents of the file, but it is not placed on my preferred location.

How can I save the file content to a preferred location?

UPDATE: I printed the full path using file.getAbsolutePath(), and I am getting the correct directory path. [D:\codes\sources\logs....\bin\logs\contents.txt] But when I look for the file in directory, I cannot find it there.

Answer

Kevin Bowersox picture Kevin Bowersox · Jul 18, 2013

Make sure you add trailing backslashes to the path parameter so the path is recognized as a directory. The example provide is for a Windows OS which uses backslashes that are escaped. For a more robust method use the file.separator property for the system.

Works

writeToFile("D:\\Documents and Settings\\me\\Desktop\\Development\\",
                "this is a test");

Doesn't Work

writeToFile("D:\\Documents and Settings\\me\\Desktop\\Development",
                "this is a test");

File Separator Example

String fs = System.getProperty("file.separator");
String path = fs + "Documents and Settings" + fs + "me" + fs
        + "Desktop" + fs + "Development" + fs;
writeToFile(path, "this is a test");