Writing to a File in Java

When working on an enterprise application, sometimes it is needed to write the text or binary data into 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.

1. Using Files.writeString() and Files.write()

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

  • As the name suggests, writeString() method is used to write the character data into files.
  • All characters are written as they are, including the line separators. No extra characters are added.
  • By default, UTF-8 character encoding is used.
  • It throws IOException if an I/O error occurs writing to or creating the file, or the text cannot be encoded using the specified charset.
Path filePath = Path.of("demo.txt");
String content  = "hello world !!";

Files.writeString(filePath, content);

Files class another method write() since Java 7 and it works similar to writeString(). The write() method can be used to write the raw data in bytes or to write the strings in lines.

Path filePath = Path.of("demo.txt");
String content  = "hello world !!";

//Write bytes
Files.write(filePath, content.getBytes());

//Write lines
List<String> lines = Arrays.asList("a", "b", "c");
Files.write(filePath, lines, StandardCharsets.UTF_8);

2. Fast Writing FileChannel and ByteBuffer

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.

Path fileName = Path.of("demo.txt");
String content  = "hello world !!";

try (
  RandomAccessFile stream = new RandomAccessFile(filePath.toFile(),"rw");
  FileChannel channel = stream.getChannel();) {

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

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

3. Using BufferedWriter

BufferedWriter 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 fewer IO operations, so it improves the performance.

Path filePath = Path.of("demo.txt");
String content  = "hello world !!";

try (BufferedWriter writer = new BufferedWriter(
  new FileWriter(filePath.toFile()))) {
  
  writer.write(content);
}

4. Using FileWriter or PrintWriter

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

Path filePath = Path.of("demo.txt");
String content  = "hello world !!";

try(FileWriter fileWriter = new FileWriter(filePath.toFile())){
  fileWriter.write(content);
}

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.

Path filePath = Path.of("demo.txt");
String content  = "hello world !!";

try(FileWriter fileWriter = new FileWriter(filePath.toFile());
  PrintWriter printWriter = new PrintWriter(fileWriter);){
  printWriter.print(content);
  printWriter.printf("Blog name is %s", "howtodoinjava.com");
}

5. 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.

Path filePath = Path.of("demo.txt");
String content  = "hello world !!";

try(FileOutputStream outputStream 
  = new FileOutputStream(filePath.toFile())){
  
  byte[] strToBytes = content.getBytes();
  outputStream.write(strToBytes);
}

6. 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.

Path filePath = Path.of("demo.txt");
String content  = "hello world !!";

try (
  FileOutputStream outputStream 
    = new FileOutputStream(filePath.toFile());
  DataOutputStream dataOutStream 
    = new DataOutputStream(new BufferedOutputStream(outputStream));) {
    
  dataOutStream.writeUTF(content);
  dataOutStream.writeInt(10);
  dataOutStream.writeLong(100L);
} 

7. 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 the preferred way of writing files in Java 8 as well.

Happy Learning !!

Source Code on Github

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

1 thought on “Writing to a File in Java”

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.