Java – Write to File

When working on enterprise application, sometimes it is needed to write files in Java e.g. writing user-generated reports into the filesystem. Though there are multiple ways of writing the files in Java, let’s quickly go through a few of them for quick reference when it is needed.

Table of Contents

Java 11 - Files.writeString()
Java NIO - Write File using FileChannel
Java NIO - Files.write()
Write File using BufferedWritter
Write File using FileWriter/PrintWriter
Write File using FileOutputStream
Write File using DataOutputStream

Files.writeString() – Since Java 11

With the method writeString() introduced in Java 11, we can write a String into a file using a single line statement.

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

public class WriteToFile 
{
	public static void main(String[] args) throws IOException 
	{
	    Path fileName = Path.of("demo.txt");
	    String content  = "hello world !!";
	    Files.writeString(fileName, content);
	    
	    String actual = Files.readString(fileName);
	    System.out.println(actual);
	}
}

Write File using FileChannel

FileChannel can be used for reading, writing, mapping, and manipulating a file.

If we are writing the large files, FileChannel can be faster than standard IO.

File channels are safe for use by multiple concurrent threads.

public static void usingFileChannel() throws IOException 
{
    String fileContent = "Hello Learner !! Welcome to howtodoinjava.com.";

    RandomAccessFile stream = new RandomAccessFile("c:/temp/samplefile6.txt", "rw");
    FileChannel channel = stream.getChannel();

    byte[] strBytes = fileContent.getBytes();
    ByteBuffer buffer = ByteBuffer.allocate(strBytes.length);

    buffer.put(strBytes);
    buffer.flip();
    channel.write(buffer);

    stream.close();
    channel.close();
}

Java 7 – Files.write()

Java 7 introduced Files utility class and we can write a file using it’s write() function, internally it’s using OutputStream to write byte array into file.

public static void usingPath() throws IOException 
{
	String fileContent = "Hello Learner !! Welcome to howtodoinjava.com.";
	Path path = Paths.get("c:/temp/samplefile7.txt");
        Files.write(path, fileContent.getBytes());
}

Java Write to File using BufferedWritter

BufferedWritter the simplest way to write the content to a file. It writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriter and OutputStreamWriter.

As it buffers before writing, so it results in less IO operations, so it improves the performance.

public static void usingBufferedWritter() throws IOException 
{
	String fileContent = "Hello Learner !! Welcome to howtodoinjava.com.";
	
	BufferedWriter writer = new BufferedWriter(new FileWriter("c:/temp/samplefile1.txt"));
	writer.write(fileContent);
	writer.close();
}

Write File using FileWriter/PrintWriter

FileWriter the most clean way to write files. Syntax is self explanatory and easy to read and understand. FileWriter writes directly into file (less performance) and should be used only when number of writes are less.

public static void usingFileWriter() throws IOException 
{
	String fileContent = "Hello Learner !! Welcome to howtodoinjava.com.";
	
	FileWriter fileWriter = new FileWriter("c:/temp/samplefile2.txt");
    fileWriter.write(fileContent);
    fileWriter.close();
}

Use PrintWriter to write formatted text to a file. This class implements all of the print methods found in PrintStream, so you can use all formats which you use with System.out.println() statements.

public static void usingPrintWriter() throws IOException 
{
	String fileContent = "Hello Learner !! Welcome to howtodoinjava.com.";
	
	FileWriter fileWriter = new FileWriter("c:/temp/samplefile3.txt");
    PrintWriter printWriter = new PrintWriter(fileWriter);
    printWriter.print(fileContent);
    printWriter.printf("Blog name is %s", "howtodoinjava.com");
    printWriter.close();
}

Write File using FileOutputStream

Use FileOutputStream to write binary data to a file. FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter.

public static void usingFileOutputStream() throws IOException 
{
	String fileContent = "Hello Learner !! Welcome to howtodoinjava.com.";
	
	FileOutputStream outputStream = new FileOutputStream("c:/temp/samplefile4.txt");
    byte[] strToBytes = fileContent.getBytes();
    outputStream.write(strToBytes);
 
    outputStream.close();
}

Write File using DataOutputStream

DataOutputStream lets an application write primitive Java data types to an output stream in a portable way. An application can then use a data input stream to read the data back in.

public static void usingDataOutputStream() throws IOException 
{
	String fileContent = "Hello Learner !! Welcome to howtodoinjava.com.";
	
	FileOutputStream outputStream = new FileOutputStream("c:/temp/samplefile5.txt");
	DataOutputStream dataOutStream = new DataOutputStream(new BufferedOutputStream(outputStream));
	dataOutStream.writeUTF(fileContent);
 
	dataOutStream.close();
}

Summary

  1. If we try to write to a file that doesn’t exist, the file will be created first and no exception will be thrown (except using Path method).
  2. Always close the output stream after writing the file content to release all resources. It will also help in not corrupting the file.
  3. Use PrintWriter is used to write formatted text.
  4. Use FileOutputStream to write binary data.
  5. Use DataOutputStream to write primitive data types.
  6. Use FileChannel to write larger files. It is preferred way in writing file in Java 8 as well.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

1 thought on “Java – Write to File”

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.