Java Write String to a File
1. Intruduction
In this tutorial, we will see different ways that Java offers to write a String into a file. We’ll make use of BufferedWriter, PrintWriter, FileOutputStream, DataOutputStream, FileChannel, and Temporary File, and the advantages that each one gives us.
2. BufferedWriter Example
In this example, we will use the BufferedWriter
class. The BufferedWriter
class can be used to write a String to a file more efficiently. The BufferedWriter
maintains an internal buffer of 8192 characters. The characters are written to an internal buffer and once the buffer is filled or the writer is closed, the string is written to the disk, reducing the usage of the disk.
bufferedWriter.java
import java.io.FileWriter; import java.io.BufferedWriter; public class bufferedWriter{ public static void main(String args[]) { String data = "This is the data i want to write to a file"; try { FileWriter file = new FileWriter("output.txt"); BufferedWriter buffer = new BufferedWriter(file); buffer.write(data); buffer.close(); } catch (Exception e) { e.getStackTrace(); } } }
3. PrintWriter Example
This class implements all of the print methods found in PrintStream
. Methods in this class never throw I/O exceptions, although some of its constructors may. PrintWriter
class write formatted representations of objects to a text-output stream. Is usually the fastest and easiest way to write String
data to a file.
printWriter.java
import java.io.PrintWriter; class printWriter { public static void main(String[] args) { String data = "This is the data i want to write to a file."; try { PrintWriter output = new PrintWriter("output2.txt"); output.println(data); output.close(); } catch (Exception e) { e.getStackTrace(); } } }
4. FileOutputStream Example
A FileOutputStream
is an output stream for writing data to a File
or to a FileDescriptor
. FileOutputStream
is meant for writing streams of raw bytes such as image data.
fileoutputStream.java
import java.io.FileOutputStream; public class fileoutputStream { public static void main(String[] args) { String data = "This is the data i want to write to a file"; try { FileOutputStream output = new FileOutputStream("output3.txt"); byte[] array = data.getBytes(); output.write(array); output.close(); } catch (Exception e) { e.getStackTrace(); } } }
- line 11: we need to transform the String array to byte[] array in order to write it.
5. DataOutputStream Example
DataOutputStream
let us write primitive Java data types to an output stream. We can then use a DataInputStream
to read the data back in.
dataoutputStream.java
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; class dataoutputStream { public static void main(String args[]) throws IOException { try (DataOutputStream out = new DataOutputStream(new FileOutputStream("output4.txt"))) { out.writeDouble(5.5); out.writeInt(100); out.writeBoolean(false); out.writeChar('C'); } catch (FileNotFoundException ex) { System.out.println("Cannot Open Output File"); return; } try (DataInputStream in = new DataInputStream(new FileInputStream("output4.txt"))) { double a = in.readDouble(); int b = in.readInt(); boolean c = in.readBoolean(); char d = in.readChar(); System.out.println("Values: " + a + " " + b + " " + c + " " + d); } catch (FileNotFoundException e) { System.out.println("Cannot Open the Input File"); return; } } }
6. FileChannel Example
With FileChannel class we are able to read, write, map, and manipulate a file. It has a current position within its file which can be both queried and modified. The size of the file increases when bytes are written beyond its current size and also decreases when it is truncated.
fileChannel.java
import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.*; import java.nio.channels.FileChannel; import java.nio.charset.StandardCharsets; public class fileChannel { public static void main(String[] args) throws IOException { try { RandomAccessFile file = new RandomAccessFile("output5.txt", "rw"); FileChannel channel = file.getChannel(); String s = "This is the data i want to write to a file"; ByteBuffer buf = ByteBuffer.allocate(48); buf.put(s.getBytes()); buf.flip(); channel.write(buf); buf.clear(); channel.read(buf); String read = new String(buf.array(), StandardCharsets.UTF_8); System.out.println(read); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
7. File Class Example with Temporary File
The temporary file is just a regular file created on a predefined directory. The File class give us methods that help us create, delete, write and get its different properties.
tempFile.java
import java.io.File; import java.io.IOException; public class tempFile { public static void main(String[] args) throws IOException { File file = File.createTempFile("random", "txt"); System.out.println("File name : " + file.getName()); System.out.println("Path : " + file.getPath()); System.out.println("Absolute path : " + file.getAbsolutePath()); System.out.println("Parent : " + file.getParent()); System.out.println("Exists : " + file.exists()); if (file.exists()) { System.out.println("Is writeable : " + file.canWrite()); System.out.println("Is readable : " + file.canRead()); System.out.println("Is a directory : " + file.isDirectory()); System.out.println("File Size in bytes : " + file.length()); } file.deleteOnExit(); } }
8. Summary
In these examples we learnt about different ways we can create, write, modify, parse files in Java. Depending on the application we want to create, we can choose a specific class that will provide us with flexibility and efficiency.
9. Download the source code
This was an example of how to create,write and read files in Java!
You can download the full source code of this example here: Java Write String to a File