Java — How to write to a File | Code Factory

Donate : Link

WordPress Blog : Link

You’ll learn how to write data to a file in Java.

Java has several ways of writing data to a File using various built-in classes like BufferedWriter, FileWriter, PrintWriter, FileOutputStream, BufferedOutputStream, DataOutputStream, RandomAccessFile, FileChannel, etc.

Each of these classes have different properties and use-cases. Let’s look at each of them with the help of examples.

Java write to File using BufferedWriter

BufferedWriter is the simplest way of writing textual data to a File. It writes text to a character-output stream and it buffers characters to improve performance.

In general, you should always try to use Buffered I/O since it writes data in chunks resulting in less I/O operations and improved performance.

package com.example.java.programming.file;import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* @author code.factory
*
*/
public class BufferedWriterExample {
public static void main(String... args) {
Path filePath = Paths.get("test.txt");
Charset charset = StandardCharsets.UTF_8;
// Instantiate a BufferedWriter
try (BufferedWriter writer = Files.newBufferedWriter(filePath, charset)) {
// Write data
writer.write("Hello, World!");
writer.newLine();
writer.write("Learn how to write data to a File efficiently using BufferedWriter");
writer.newLine();
} catch (IOException ex) {
System.out.format("I/O error: %s%n", ex);
}
}
}

Java write to File using PrintWriter

PrintWriter class allows you to write formatted textual data to a File. It implements all of the print methods found in PrintStream, so you can use

package com.example.java.programming.file;import java.io.BufferedWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* @author code.factory
*
*/
public class PrintWriterExample {
public static void main(String... args) {
Path filePath = Paths.get("test.txt");
Charset charset = StandardCharsets.UTF_8;
// Instantiate a new FileWriter by wrapping a buffered writer for improved performance
try (BufferedWriter bufferedWriter = Files.newBufferedWriter(filePath, charset)) {
PrintWriter printWriter = new PrintWriter(bufferedWriter);
// Write formatted data using print writer
printWriter.println("Hello, World!");
printWriter.printf("The value of PI is %f\n", Math.PI);
printWriter.println(123456L);
printWriter.println(true);
} catch (IOException ex) {
System.out.format("I/O error: %s%n", ex);
}
}
}

Java write to File using FileWriter

You can also use FileWriter for writing textual data to a File. But note that, it doesn’t support buffering so it’ll be slow compared to BufferedWriter. You can use this when your number of writes are less.

package com.example.java.programming.file;import java.io.FileWriter;
import java.io.IOException;
/**
* @author code.factory
*
*/
public class FileWriterExample {
public static void main(String... args) {
// Instantiate a new FileWriter
try (FileWriter fileWriter = new FileWriter("test.txt")) {
// Write data
fileWriter.write("Hello, World!\n");
fileWriter.write("Learn how to write data to a File using FileWriter\n");
} catch (IOException ex) {
System.out.format("I/O error: %s%n", ex);
}
}
}

Java write to File using BufferedOutputStream

The Writer classes whose examples are given earlier in this article are used when you need to write textual data (data represented as characters) to a file.

But If you want to write binary data (or streams of raw bytes such as image data) to a file, then you need to use byte streams.

Since textual data can also be considered as a stream of bytes, you can use byte streams for textual data as well.

The following examples shows how to write binary data to a file using BufferedOutputStream.

package com.example.java.programming.file;import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* @author code.factory
*
*/
public class BufferedOutputStreamExample {
public static void main(String... args) {
String data = "This example shows how to Write data to a File using BufferedOutputStream";
// Create a BufferedOutputStream by wrapping a FileOutputStream
try (OutputStream outputStream = Files.newOutputStream(Paths.get("test.txt"));
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream)) {
// Write binary data to a file
bufferedOutputStream.write(data.getBytes());
} catch (IOException ex) {
System.out.format("I/O error: %s%n", ex);
}
}
}

Java write to File using FileOutputStream

You can also use FileOutputStream directly for writing binary data to a File. But it will be less performant than BufferedOutputStream because it will call the underlying system for each byte written instead of buffering data and writing it in chunks.

package com.example.java.programming.file;import java.io.FileOutputStream;
import java.io.IOException;
/**
* @author code.factory
*
*/
public class FileOutputStreamExample {
public static void main(String... args) {
String data = "This example shows how to Write data to a File using FileOutputStream";
// Instantiate a new FileOutputStream
try (FileOutputStream outputStream = new FileOutputStream("test.txt")) {
// Write data in the form of bytes
outputStream.write(data.getBytes());
} catch (IOException ex) {
System.out.format("I/O error: %s%n", ex);
}
}
}

Java write to File using DataOutputStream

DataOutputStream lets you write primitive Java data types to an output stream in a portable way.

package com.example.java.programming.file;import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* @author code.factory
*
*/
public class DataOutputStreamExample {
public static void main(String... args) {
// Create a DataOutputStream by wrapping a BufferedOutputStream for improved
// performance
try (OutputStream outputStream = Files.newOutputStream(Paths.get("test.txt"));
DataOutputStream dataOutputStream = new DataOutputStream(new BufferedOutputStream(outputStream))) {
// Write primitive Java data types
dataOutputStream.writeUTF("Hello!");
dataOutputStream.writeLong(Long.MAX_VALUE);
dataOutputStream.writeDouble(3.14);
dataOutputStream.writeBoolean(true);
} catch (IOException ex) {
System.out.format("I/O error: %s%n", ex);
}
}
}

Java write to File using RandomAccessFile

RandomAccessFile lets you write data at a specific position in a file. It behaves like a large array of bytes stored in the file system. It maintains a cursor, or index into the implied array, called the file pointer.

Output operations write bytes starting at the file pointer and advance the file pointer past the bytes written. Output operations that write past the current end of the implied array cause the array to be extended.

You can get the current position of the file pointer using getFilePointer() method and set it using the seek() method.

package com.example.java.programming.file;import java.io.IOException;
import java.io.RandomAccessFile;
/**
* @author code.factory
*
*/
public class RandomAccessFileExample {
public static void main(String... args) {
try (RandomAccessFile randomAccessFile = new RandomAccessFile("test.txt", "rw")) {
randomAccessFile.seek(10);
randomAccessFile.writeChar('-');
randomAccessFile.writeInt(123456);
randomAccessFile.writeChar('-');
} catch (IOException ex) {
System.out.format("I/O error: %s%n", ex);
}
}
}

Java write to File using FileChannel

FileChannel supports reading, writing, mapping, and manipulating a file. You can obtain a FileChannel from a RandomAccessFile by calling its getChannel() method. If you’re dealing with large files, a FileChannel can be faster than Standard I/O.

package com.example.java.programming.file;import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* @author code.factory
*
*/
public class FileChannelExample {
public static void main(String... args) {
String data = "This example shows how to write to a File using FileChannel. \n"
+ "FileChannel can be faster thant standard I/O if you're dealing with large files";
try (RandomAccessFile randomAccessFile = new RandomAccessFile("test.txt", "rw");
FileChannel fileChannel = randomAccessFile.getChannel()) {
// Create a byte buffer with sufficient capacity to accommodate the data.
byte[] byteData = data.getBytes();
ByteBuffer buffer = ByteBuffer.allocate(byteData.length);
// Transfer the content of the byte array to the buffer
buffer.put(byteData);
// Move to the start position to prepare for channel write
buffer.flip();
// Writes a sequence of bytes to the channel from the given buffer.
fileChannel.write(buffer);
} catch (IOException ex) {
System.out.format("I/O error: %s%n", ex);
}
}
}

Java write to File using Java NIO’s Files.Write

Finally, there is a simple Files.write() method in the java.nio.file.Files class that you can use to write data to a File. This is often used for small files. You should prefer BufferedWriter or BufferedOutputStream for large files.

package com.example.java.programming.file;import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* @author code.factory
*
*/
public class FilesWriteExample {
public static void main(String... args) throws IOException {
String data = "This example shows how to write a sequence of bytes to a File using Files.write method.";
Path path = Paths.get("test.txt"); Files.write(path, data.getBytes());
}
}