Search code examples
javafilewriter

FileWriter not writing to file with protocol in URL


I am using the code below to write to file.

FileWriter writer = new FileWriter(outputPath);
writer.append(prettyJson);
writer.flush();
writer.close();

I notice that the content is not written to the file path starts with "file://". Any specific reason for this ?


Solution

  • When Java talks about filenames in the form of String, the documentation usually says

    The system-dependent filename

    and thus it is expecting an "everyday" filename, like filename.ext, or something like c:\some\path\filename.ext on Windows, or /some/path/filename.ext on Unix-likes (this one actually works on both, Java accepts / as path separator on Windows too)

    For a filename with file:// protocol, use URI and wrap it into a File:

    FileWriter writer = new FileWriter(new File(new URI(outputPath)));