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.

To see different options available for reading a file in Java, check this post How to Read File in Java

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

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class WriteToFile {
  public static void main(String[] args) {
    writeFile("D:\\test.txt");
  }
	
  private static void writeFile(String fileName){
    BufferedWriter bw = null;
    try {
      // wrapping FileWriter instance
      bw = new BufferedWriter(new FileWriter(fileName));
      bw.write("This is a test line");
      bw.newLine();
      bw.write("Line written by Java program in knpCode.com");
    }catch (IOException exp){
      exp.printStackTrace();
    }finally{
      if(bw != null){
        try {
          bw.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
  }
}

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.

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class WriteToFile {
  public static void main(String[] args) {
    writeFile("D:\\test.txt");
  }
	
  private static void writeFile(String fileName){
    BufferedOutputStream bw = null;
    try {
      bw = new BufferedOutputStream(new FileOutputStream(fileName));
      // may have to use \r\n for Windows OS
      bw.write("This is a test line\n".getBytes());
      bw.write("Line written by Java program in knpCode.com".getBytes());
    }catch (IOException exp){
      exp.printStackTrace();
    }finally{
      if(bw != null){
        try {
          bw.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
  }
}

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.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class WriteToFile {
  public static void main(String[] args) {
    String content = "This is a test line.\nLine written by Java program in knpCode.com.";
    try {
      Files.write(Paths.get("D:\\test.txt"), content.getBytes());
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

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

public class WriteToFile {

  public static void main(String[] args) {
    BufferedWriter bw = null;
    String content = "This is a test line.\nLine written by Java program in knpCode.com.";
    try {
      bw = Files.newBufferedWriter(Paths.get("D:\\test.txt"));
      bw.write(content);			 
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }finally{
      if(bw != null){
        try {
          bw.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
  }
}

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

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class WriteToFile {
  public static void main(String[] args) {
    String content = "This is a test line.\nLine written by Java program in knpCode.com.";		
    try (BufferedWriter bw = Files.newBufferedWriter(Paths.get("D:\\test.txt"))) {
      bw.write(content);			 
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Related Posts

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.