Approaches to write files in Java

This article describes some of the common approaches to write files in Java.

Using OutputStreamWriter with a BufferedReader

Refer the example function below. FileOutputStream is the byte stream here capable of writing raw bytes to the file. OutputStreamWriter is a bridge which converts characters into raw bytes using the specified charset. The OutputStreamWriter is a unbuffered stream. To make the program efficient for writing characters, lines etc. it needs to be wrapped with a buffered stream like the BufferedWriter.

public static void writeStringToFile1(String str) {BufferedWriter writer = null;try {File file = new File("output/test1.txt");if ( ! file.exists() )file.createNewFile();FileOutputStream fos = new FileOutputStream(file);OutputStreamWriter out = new OutputStreamWriter(fos, StandardCharsets.UTF_8);writer = new BufferedWriter(out);writer.write(str);writer.flush();} catch ( IOException e ){e.printStackTrace();}finally {try {if ( writer != null )writer.close();} catch (IOException e) {e.printStackTrace();}}}

Using FileWriter with a BufferedWriter

Refer the example function below. FileWriter is a convenience class for writing character files. FileWriter assumes the default character encoding. FileWriter is unbuffered and we need to wrap it in a buffered stream to make the program more efficient for reading.

public static void writeToFile2(String str) {BufferedWriter out = null;try {File file = new File("output/test2.txt");if ( ! file.exists() )file.createNewFile();FileWriter writer = new FileWriter(file);out = new BufferedWriter(writer);out.write(str);out.flush();} catch ( IOException e ){e.printStackTrace();}finally {if ( out != null ) {<      try {out.close();} catch ( IOException e ){e.printStackTrace();}}}}

Using PrintWriter with a BufferedWriter 

Refer the example function below. PrintWriter has the capability to print formatted representations of objects to a text output stream. 

public static void writeToFile3(String str) {PrintWriter out = null;try {File file = new File("output/test3.txt");if ( ! file.exists() )file.createNewFile();BufferedWriter writer = new BufferedWriter(new FileWriter(file));out = new PrintWriter(writer);out.println(str);// Write formatted outputout.println(true);out.println(123.00);out.printf("%5dn", 100);out.flush();} catch ( IOException e ){e.printStackTrace();}finally {if ( out != null ) {out.close();}}}

Using Files for Java7

Java7 has introduced the new file I/O package which provides the Files API to make writing files much simpler. Refer example below.

public static void writeUsingJava7(String str) {try {Files.write(Paths.get("output/test10.txt"),str.getBytes(),StandardOpenOption.CREATE);} catch (IOException e) {e.printStackTrace();}}