Java write to file

Writing a file is a task which every developer is required to perform. Java provides many different ways to write to a file.
Following are the methods that demonstrate how to write a string to file in java

1. Write FileOutputStream to file
java.io.FileOutputStream can be used for writing binary files such as audio, video, image files etc. It can also be used to write a text file.
FileoutputStream example to write a file in java is given below.

import java.io.FileOutputStream;
import java.io.File;
import java.io.IOException;

public class FileOutputStreamWriter {	
   public static void main(String[] args) {
      String outFilePath = "D:/out.txt";
      FileOutputStream fout = null;
      String textToWrite = "Dummy text";
      try {
        // initialize stream
        fout = new FileOutputStream(new File(outFilePath));
        // convert string to byte array
        byte[] buffer = textToWrite.getBytes();
        // write byte array to file 
        fout.write(buffer);
      } catch (IOException e) {
          e.printStackTrace();
      } finally {
          // close stream
          try {
            if(fout != null) {
              fout.close();
            }
          } catch (IOException e) {
            e.printStackTrace();
         }
      }
   }
}

Explanation
java.io.FileOutputStream writes the data in the form of bytes. It has a read() method which accepts a byte array as argument and writes it to the file.
String to be written to the file is converted to a byte array using getBytes() method

After the file is written completely, do not forget to close the streams.

From java 7 and above, you can modify the try-catch block in the above example using try-with-resources statement as shown below.

try (FileOutputStream fout = 
            new FileOutputStream(new File(outFilePath))) {
     // code to write the file
} catch (IOException e) {
     e.printStackTrace();
}

With this construct, you do need to write finally block just to close the streams as it will be done automatically when the try block completes.
2. FileWriter to file
java.io.FileWriter class can be used to write a text file in java. It writes a character array to an output file.

FileWriter example to write a file in java is given below.

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class WriteFileUsingWriter {	
   static void main(String[] args) {
      String outFilePath = "D:/out.txt"; 
      String textToWrite = "Dummy text";
      FileWriter fwr = null;
      try {
         // initialize writer
         fwr = new FileWriter(outFilePath);
         // get characters
         char[] chars = textToWrite.toCharArray();
         // write array to file
         fwr.write(chars);
         }
      } catch (IOException e) {
         e.printStackTrace();
      } finally {
         // close writer
         try {
           if (fr != null) {
             fr.close();
           }
           if (fwr != null) {
             fwr.close();
           }
         } catch (IOException e) {
           e.printStackTrace();
         }
      }
   }
}

Explanation
FileWriter has a write() method which accepts a character array as argument and writes it to a file.
The string to be written to the file is converted to a character array using its toCharArray() method.

FileWriter is created using its constructor which accepts the path of file to be written as argument.

http://method33. BufferedWriter to file
This method is used to write a text file line by line. java.io.BufferedWriter has a write() method that accepts a string argument which is written to a file.
Thus, this method can be used to write a string to a file. Also, this method is efficient and fast as compared to the methods described above since it involves lesser number of IO operations.

BufferedWriter example to write a text file is given below.

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class WriteFileUsingBufferedWriter {	
   public static void main(String[] args) {
      String filePath = "D:/out.txt";
      BufferedWriter bwr = null;
      String textToWrite = "Dummy text";
      try {
         // initialize writer
         bwr = new BufferedWriter(new FileWriter(outFilePath));
         bwr.write(textToWrite);
      } catch (IOException e) {
         e.printStackTrace();
      } finally {
         // close writer
         try {
           if (bwr != null) {
             bwr.close();
           }
         } catch (IOException e) {
           e.printStackTrace();
         }
      }
   }
}

Java 8 introduced a new method to create an object of BufferedWriter using java.nio.Files class.
Files class was added in java 7 and is discussed below.
It has a newBufferedWriter() method that takes an object of java.nio.file.Path and returns a BufferedWriter.
So, above example can be modified as

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files; 
import java.nio.file.Path;
public class WriteFileUsingBufferedWriter {	
   public static void main(String[] args) {
      Path path = Paths.get("D:/out.txt");
      BufferedWriter bwr = null;
      String textToWrite = "Dummy text";
      try {
         // initialize writer
         bwr = Files.newBufferedWriter(path);
         bwr.write(textToWrite);
      } catch (IOException e) {
         e.printStackTrace();
      } finally {
         // close writer
         try {
           if (bwr != null) {
             bwr.close();
           }
         } catch (IOException e) {
           e.printStackTrace();
         }
      }
   }
}

4. RandomAccessFile
java.io.RandomAccessFile class can be used for writing to a file. It has a write() method which accepts a byte array as argument.
For writing a string to the file, convert the string to a byte array with its getBytes() method.

An instance of RandomAccessFile can be created using its constructor which takes 2 arguments:
First, path of file to be written.
Second, mode of opening the file. For writing to a file, it should be “rw”, “rws” or “rwd”.

Code example follows.

import java.io.RandomAccessFile;
import java.io.IOException;

public class WriteUsingChannel {	
  public static void main(String[] args) {
    String outFilePath = "D:/out.txt"; 
    String textToWrite = "Dummy text";
    RandomAccessFile fileAccessForWrite = null;
    try {
      fileAccessForWrite = new RandomAccessFile(outFilePath, "rw");
      fileAccessForWrite.write(textToWrite.getBytes());
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

5. Java nio Files class
java.nio.file.Files class has a writeString() method which can be used to write a file.

Files has a static writeString() method which takes following arguments:

1. path of file. This should be an object of java.nio.file.Path.
2. string to be written to the file.
3. mode in which the file is opened, that is, write. This is provided as an enum StandardOpenOption.

Code example is given below.

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

public class FilesExample {
   public static void main(String[] args) {
      Path path = Paths.get("E:/test.txt");
      try {
         Files.writeString(path, "Dummy text", 
                           StandardOpenOption.WRITE);
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

This method was added in java 11.

Let’s tweak in

1. All write() methods throw an IOException since many kinds of errors may arise during both these operations such as file is corrupt, there are no write permissions, no disk space, file removed from its location etc.

2. FileOutputStream, FileWriter both have constructors which take a File object or a file name in String format as arguments.

3. FileOutputStream operates over bytes and is more suitable for binary files such as images, jars etc. while java.io.FileWriter deals with characters and is more suitable for text files.

4. BufferedWriter is faster as compared to FileOutputStream and FileWriter, as it writes a complete line in one go.

5. Closing a BufferedWriter closes the underlying Writer and there is no need to close it explicitly.

6. If you are using jdk 7 and above for development and declare the file stream or writer objects as

try(FileOutputStream fin = new FileOutputStream(new File(filePath)))

you don’t need to explicitly close the stream or reader.
This is called try-with-resources construct.

Hope the article was useful in understanding how to write to a file in java.

Leave a Reply