Different ways to write to a file using Java

Last Updated On Thursday 9th Jun 2022

Write With BufferedWriter

  • Use BufferedWriter to write a String to a new file.
	public void whenWriteStringUsingBufferedWritter_thenCorrect() 
  throws IOException {
    String str = "New String Here";
    BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
    writer.write(str);

    writer.close();
}
	

The output will be

	New String Here
	

We can then append a String to the existing file.

	@Test
public void whenAppendStringUsingBufferedWritter_thenOldContentShouldExistToo() 
  throws IOException {
    String str = "String Here";
    BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
    writer.append(' ');
    writer.append(str);

    writer.close();
}
	

The output will be

	String Here
	

Write With PrintWriter

We use PrintWriter to write formatted text to a file.

	@Test
public void givenWritingStringToFile_whenUsingPrintWriter_thenCorrect() 
  throws IOException {
    FileWriter fileWriter = new FileWriter(fileName);
    PrintWriter printWriter = new PrintWriter(fileWriter);
    printWriter.print("Novel Name");
    printWriter.printf("The Product name is %name and its price is %d $", "Open Water", 13);
    printWriter.close();
}

	

The resulting file will contain

	Novel Name
The product name is Open Water, and its price is $13
	
  • Note how we’re not only writing a raw String to a file.
  • But also some formatted text with the printf method.

Write With FileOutputStream

  • Now we can use DataOutputStream to write a String to a file
	@Test
public void givenWritingToFile_whenUsingDataOutputStream_thenCorrect() 
  throws IOException {
    String value = "Hello";
    FileOutputStream fos = new FileOutputStream(fileName);
    DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos));
    outStream.writeUTF(value);
    outStream.close();

    // verify the results
    String result;
    FileInputStream fis = new FileInputStream(fileName);
    DataInputStream reader = new DataInputStream(fis);
    result = reader.readUTF();
    reader.close();

    assertEquals(value, result);
}
	

Write With RandomAccessFile

  • How to write and edit inside an existing file rather than just writing to a completely new file or appending to an existing one.
  • We need random access for it.
  • RandomAccessFile enables us to write at a specific position in the file given the offset.
	private void writeToPosition(String filename, int data, long position) 
  throws IOException {
    RandomAccessFile writer = new RandomAccessFile(filename, "rw");
    writer.seek(position);
    writer.writeInt(data);
    writer.close();
}

	
  • If we want to read the int stored at a specific location, we can use this method
	private int readFromPosition(String filename, long position) 
  throws IOException {
    int result = 0;
    RandomAccessFile reader = new RandomAccessFile(filename, "r");
    reader.seek(position);
    result = reader.readInt();
    reader.close();
    return result;
}
	

Let’s write an integer, edit it, and finally read it back to test our functions.

	@Test
public void whenWritingToSpecificPositionInFile_thenCorrect() 
  throws IOException {
    int data1 = 2014;
    int data2 = 1500;

    writeToPosition(fileName, data1, 4);
    assertEquals(data1, readFromPosition(fileName, 4));

    writeToPosition(fileName2, data2, 4);
    assertEquals(data2, readFromPosition(fileName, 4));
}

	

Write With FileChannel

FileChannel can be faster than standard IO. The following code writes String to a file using FileChannel.

	@Test
public void givenWritingToFile_whenUsingFileChannel_thenCorrect() 
  throws IOException {
    RandomAccessFile stream = new RandomAccessFile(fileName, "rw");
    FileChannel channel = stream.getChannel();
    String value = "Hello";
    byte[] strBytes = value.getBytes();
    ByteBuffer buffer = ByteBuffer.allocate(strBytes.length);
    buffer.put(strBytes);
    buffer.flip();
    channel.write(buffer);
    stream.close();
    channel.close();

    // verify
    RandomAccessFile reader = new RandomAccessFile(fileName, "r");
    assertEquals(value, reader.readLine());
    reader.close();
}
	

Write With Files Class

Using the Files class, we can create, move, copy, and delete files and directories. File Class can also use it to read and write to a file.

	@Test
public void givenUsingJava7_whenWritingToFile_thenCorrect() 
  throws IOException {
    String str = "Hello";

    Path path = Paths.get(fileName);
    byte[] strToBytes = str.getBytes();

    Files.write(path, strToBytes);

    String read = Files.readAllLines(path).get(0);
    assertEquals(str, read);
}

	

Write to a Temporary File

  • Now, let’s try to write to a temporary file.
  • The following code creates a temporary file and writes a String to it
	@Test
public void whenWriteToTmpFile_thenCorrect() throws IOException {
    String toWrite = "Hello";
    File tmpFile = File.createTempFile("test", ".tmp");
    FileWriter writer = new FileWriter(tmpFile);
    writer.write(toWrite);
    writer.close();

    BufferedReader reader = new BufferedReader(new FileReader(tmpFile));
    assertEquals(toWrite, reader.readLine());
    reader.close();
}
	

It’s just the creation of the temporary file that is interesting and different. After that point, writing to the file is the same.