Saturday, January 22, 2022

Write to a File in Java

In this post we'll see different ways to write to a file in Java. Examples given here to write to a file in Java are based on the following options-

  • BufferedOutputStream- BufferedOutputStream is a wrapper class over the OutputStream class and it adds buffering capability to the output stream. See example.
  • BufferedWriter- Writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings. See example.
  • Files Class methods- Java 7 onward Files class can be used for writing to a file in Java using Files.write() method. There is also a newBufferedWriter method in the Files class that can be used to write to a file. See example.

Refer How to append to a file in Java to see how to append to an already existing file.

Java program to write to a file using BufferedOutputStream

Though Java provides classes like FileOutputStream and FileWriter to write files using byte stream and character stream respectively but using them directly will slow down the I/O operation considerably. It is always advisable to use BufferedOutputStream or BufferedWriter to write to a file in Java because that will provide buffering to the output streams and won't cause a call to the underlying system for each byte written. Buffered output streams write data to a buffer, and the native output API is called only when the buffer is full, making I/O operation more efficient.

It is same as reading file using BufferedReader where again you get the advantage of using buffered I/O streams. In case of Buffered input streams data is read from a memory area known as a buffer which makes reading more efficient.

The write method of the BufferedOuputStream takes either a byte array or an int as an argument thus you have to call getBytes() on any String that is passed to the write method. Here one thing to note is– If your file contains character data, the best approach is to use character streams like BufferedWriter. Byte streams should only be used for the most primitive I/O.

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

public class FileWriteDemo {
 public static void main(String[] args) {
  writeFileContent("G:\\test.txt");
 }
 
 private static void writeFileContent(String fileName){
  BufferedOutputStream bs = null;
  try {
   bs = new BufferedOutputStream(new FileOutputStream(fileName));
   bs.write("Writing one line".getBytes());
   // For windows, only \n for linux
   bs.write("\r\n".getBytes());
   bs.write("Writing second line".getBytes());
   
  } catch (IOException ioExp) {
   // TODO Auto-generated catch block
   ioExp.printStackTrace();
  }finally{
   if(bs != null){
    try {
     bs.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  }
 }
}

Java program to write to a file using BufferedWriter

BufferedWriter class has two constructors for specifying the buffer size or using the default size while writing to a file.

  • BufferedWriter(Writer out)- Creates a buffered character-output stream that uses a default-sized output buffer.
  • BufferedWriter(Writer out, int sz)- Creates a new buffered character-output stream that uses an output buffer of the given size.
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class FileWrite {
 public static void main(String[] args) {
  writeFileContent("G:\\test1.txt");
 }
 
 private static void writeFileContent(String fileName){
  //BufferedWriter bw = null;
  // Using try-with-resources here 
  try(BufferedWriter bw = new BufferedWriter(new FileWriter(fileName))) {
   //bw = new BufferedWriter(new FileWriter(fileName));
   bw.write("Writing one line");
   bw.newLine();
   bw.write("Writing second line");
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

Note that in this program try-with-resources is used to automatically manage resources. It is available from Java 7 and above.

Java program to write a file using Files class methods

In Java 7 Files class is added which provides write() method to write to a file in Java. There is also a newBufferedWriter method that can be used to write to a file. There are 2 overloaded versions of write method, note that one of them is added in Java 8.

  • public static Path write(Path path, byte[] bytes,OpenOption... options) throws IOException– Write bytes to a file specified by the path. Options varargs specifies whether new file is created for writing or bytes are appended to an already existing file. If no options are present then this method works as if the  CREATE, TRUNCATE_EXISTING, and WRITE options are present.
  • public static Path write(Path path, Iterable<? extends CharSequence> lines, Charset cs, OpenOption... options) throws IOException- Write lines of text to a file. Each line is a char sequence and is written to the file in sequence with each line terminated by the platform's line separator, as defined by the system propertyline.separator. Characters are encoded into bytes using the specified charset.

Using Files.write() method to write to a file

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

public class FileWrite8 {
 public static void main(String[] args) {
  String content = "This is the line to be added.\nThis is another line.";
  try {
   Files.write(Paths.get("G://test.txt"), content.getBytes());
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

Here note that String is converted to Byte array and also there is no option parameter which means creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0 if it exists.

Using Files.newBufferedWriter method

You can also use Files.newBufferedWriter() method to write to a file in Java.

There are 2 overloaded versions of newBufferedWriter method, note that one of them is added in Java 8.

  • public static BufferedWriter newBufferedWriter(Path path, OpenOption... options) throws IOException - Opens or creates a file for writing, returning a BufferedWriter to write text to the file in an efficient manner. Options parameter specifies whether new file is created for writing or bytes are appended to an already existing file. If no options are present then this method works as if the CREATE,  TRUNCATE_EXISTING, and WRITE options are present.
  • public static BufferedWriter newBufferedWriter(Path path, Charset cs,OpenOption... options) throws IOException - Opens or creates a file for writing, returning a BufferedWriter that may be used to write text to the file in an efficient manner. Here path is the path to the file, cs is the charset to use for encoding and options parameter specifies how the file is opened.
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileWrite8 {
 public static void main(String[] args) {
  Path path = Paths.get("G://test.txt");
  try (BufferedWriter writer = Files.newBufferedWriter(path)) {
      writer.write("Hello World");
      writer.newLine();
      writer.write("Hello again");
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

Here note that no option parameter is given which means creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0 if it exists.

That's all for this topic Write to a File in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Reading Delimited File in Java Using Scanner
  2. How to Append to a File in Java
  3. How to Read File From The Last Line in Java
  4. Zipping Files in Java
  5. Try-With-Resources in Java Exception Handling

You may also like-

  1. Arrange Non-Negative Integers to Form Largest Number - Java Program
  2. Getting All The Schemas in a DB - Java Program
  3. Print Odd-Even Numbers Using Threads And wait-notify
  4. How to Convert Date And Time Between Different Time-Zones in Java
  5. Polymorphism in Java
  6. Difference Between Comparable and Comparator in Java
  7. Just In Time Compiler (JIT) in Java
  8. Different Bean Scopes in Spring