-1

What is the difference between these two?

Path path = FileSystems.getDefault().getPath("file.txt");
BufferedWriter bw = Files.newBufferedWriter(path);

and

BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("file.txt"));

Which of these two methods is better?

HNP
  • 35
  • 1
  • 7
  • I believe there is no real difference, despite the first one not being available in very old version of Java (also have a look at [Path.of](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/nio/file/Path.html#of(java.lang.String,java.lang.String...)) (does the same as the `FileSystems` solution)) – user85421 Mar 12 '20 at 07:37
  • I will go out on a limb and state that the second is better because simpler all round. The only real reason to use the first would be if you wanted to write to an oddball filesystem like a ZIP file. – user207421 Mar 12 '20 at 07:46
  • @user207421 substitute first line by `Path.of("file.txt")` and inline in second line - both are equally simple IMHO (but probably I would also use second (more used to it)) – user85421 Mar 12 '20 at 07:56
  • @user85421 I said 'simpler *all round*'. That doesn't just cover the one line of user code: it includes the underlying implementation, especially the data path to the target file. – user207421 Mar 12 '20 at 07:57

1 Answers1

1

The default character set used by Files.newBufferedWriter is UTF8, but in pre-JDK18 JVM new FileWriter will default to your Java platform System property file.encoding which might not be UTF8.

If you are the writer and reader of the file it's safest to use the UTF8 versions - using Files.newBufferedReader/Writer, or supply the character set parameter to either style FileReader/Writer / Files.newBufferedReader/Writer.

This avoids problems when deploying the same application in multiple JDKs and/or locations where the default character set might differ, as you may write files in one location which appear to be corrupt to the same application reading from different location.

As of JDK18 the work for JEP 400: UTF-8 by Default means that the default charset for FileWriter is also UTF-8 and the former platform default is stored as new system property native.encoding. If you use FileWriter in pre-JDK18 without specifying the character encoding it will be a good idea to test and fix your applications before upgrading to JDK18+. This can be done with:

// pre-JDK18 only:
java -Dfile.encoding=UTF-8 ...

The JEP mentions file.encoding=COMPAT mode to keep the pre-JDK18 behaviour when running JDK18+ so you could mix JDK18 + pre-JDK18 deployments or allow more time to resolve the character set definitions. The JEP also suggests a way to determine the traditional environment-driven selection for the default charset.

DuncG
  • 12,137
  • 2
  • 21
  • 33