Search code examples
javajava-iobufferedwriter

create java.io.BufferedWriter using java.nio.Files or java.io classes


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?


Solution

  • 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.