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 ?

4 Answers

2
tevemadar On Best Solutions

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)));
3
finomnis On

Simple. You have to stick to the documentation. And the documentation clearly specifies: https://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter(java.io.File)

fileName - String The system-dependent filename.

System-dependent means:

  • /path/to/file on Linux / Mac
  • C:\path\to\file on Windows

file:// is not a filename, but a URL, and most commonly used in browsers.

1
GhostCat On

The javadoc says:

public FileWriter(String fileName) throws IOException

Constructs a FileWriter object given a file name.

Thus: when using this interface, you can not pass an URL, or URI or anything that legally could start with file://.

In other words: this works as designed. This constructor expects a file name, plain and simple.

If you have a URL-like string, try something like this:

URL fileURL = new URL("file://C:/whatever.txt");
InputStream is = fileURL.openStream();

Or simply create a File object from that UIR you got. To then pass that file object to a the slightly different constructor of FileWriter.

1
Matthew Cain On

If you are trying to use a relative path go for:

FileWriter fw = new FileWriter("./" + fileName, true);