简体   繁体   中英

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 ?

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.

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

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.

如果您尝试使用相对路径,请执行以下操作:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM