How to Write to a File in Java

This post shows various options to write to a file in Java.

In Java there are two classes FileWriter and FileOutputStream for writing to a file. Out of these two FileWriter is meant for writing streams of characters and FileOutputStream is used for writing streams of raw bytes.

In general, a Writer sends its output immediately to the underlying character or byte stream. Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters.

So the classes you should use for writing to a file in Java are BufferedWriter and BufferedOutputStream.

Apart from these classes Files class added in Java 7 also provides methods for writing to a file in Java. There is Files.write() method to write bytes to a file. There is also a Files.newBufferedWriter() method which returns a BufferedWriter that may be used to write text to the file in an efficient manner.

So there are four options for writing to a file in Java-

  1. Using BufferedWriter
  2. Using BufferedOutputStream
  3. Using Files.write() method
  4. Using Files.newBufferedWriter() method

Java program to write to a file using BufferedWriter

Java program to write to a file using BufferedOutputStream

If you have to write raw bytes then you can use BufferedOutputStream class. In the example code getBytes() method is used to encode string into bytes.

Java program to write to a file using Files.write() method

This method Writes bytes to a file so the content has to be passed as byte array.

Java program to write to a file using Files.newBufferedWriter() method

In Java 7 you can also use try-with-resources to close the resources automatically rather than closing them explicitly using finally block.

That’s all for the topic How to Write to a File in Java. If something is missing or you have something to share about the topic please write a comment.

You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.