Many enterprises application need to write content in the file. For example, creating a report or invoice files. The problem is how you will do with Java Write to File? There are many ways to do it, In this tutorial, we will discuss different ways to java write to file with examples.
Writing a file in Java ways
Here are some different ways to write a file in java.
- BufferedWritter
- FileWriter – Writes directly into the file
- PrintWriter – Write formatted text.
- FileOutputStream – Write binary data.
- DataOutputStream – Write primitive data types
- FileChannel – Write larger files
- Write File using Java 7 Path
Let’s start Java Write to File example with different ways
We will look at a quick and very simple way with short details about how to write files. If we tried a write file and this file not exists then it will throw an error, so always use try-catch block or use exception handling. Most of the examples are based on Java write a string to file.
BufferedWritter
The simplest to write a file in java used BufferedWritter, which writes text to a character-output stream. So it more efficient writing of single Characters, Strings, and Arrays.
See the below example. You needed a written code in try-catch exception handling because there is a lot of chance of error. Like not found file error etc.
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class FileWriting { public static void main(String arg[]) { String fileContent = "Hello BufferedWriter file writing "; try { BufferedWriter writer = new BufferedWriter(new FileWriter("samplefile.txt")); writer.write(fileContent); writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
Here is a gif presentation of the project file and code output.
Java Write File using FileWriter/PrintWriter
FileWriter writes directly into the file. Its performance is less than others so use only when you want a write less. Its syntax is clean and easy, see the below example. It will remove the old content of the file if any there.
import java.io.FileWriter; import java.io.IOException; public class FileWriting { public static void main(String arg[]) { String fileContent = "Hello FileWriter "; try { FileWriter fileWriter = new FileWriter("samplefile.txt"); fileWriter.write(fileContent); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } }
PrintWriter is used when you want a write a file in formate. It has some advantages because this class implements all of the print methods found in,PrintStream
so you can use all formats. And you can also use it with System.out.println()
statements.
See the code, you will get an idea of how printf the other methods can use here.
public class FileWriting { public static void main(String arg[]) { String fileContent = "Hello PrintWriter "; try { FileWriter fileWriter = new FileWriter("samplefile.txt"); PrintWriter printWriter = new PrintWriter(fileWriter); printWriter.print(fileContent); printWriter.printf("writing another string"); printWriter.close(); } catch (IOException e) { e.printStackTrace(); } } }
FileOutputStream
With FileOutputStream you can write binary data in a file. For an example writing an image row data.
import java.io.FileOutputStream; import java.io.IOException; public class FileWriting { public static void main(String arg[]) { String fileContent = "Hello FileOutputStream "; try { FileOutputStream outputStream = new FileOutputStream("samplefile.txt"); byte[] strToBytes = fileContent.getBytes(); outputStream.write(strToBytes); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
DataOutputStream
When you want a write primitive Java data types, DataOutputStream is a portable way. Possible read back data from a file.
import java.io.*; public class FileWriting { public static void main(String arg[]) { String fileContent = "Hello FileOutputStream"; try { FileOutputStream outputStream = new FileOutputStream("c:/temp/samplefile5.txt"); DataOutputStream dataOutStream = new DataOutputStream(new BufferedOutputStream(outputStream)); dataOutStream.writeUTF(fileContent); dataOutStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
FileChannel
When you want a write a larger file use FileChannel. It’s used for reading, writing, mapping, and manipulating a file. It’s faster than standard IO in larger file cases.
File channel also safe at multiple concurrent threads. See example for it.
import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class FileWriting { public static void main(String arg[]) { String fileContent = "Hello File channel"; try { RandomAccessFile stream = new RandomAccessFile("samplefile.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(); } catch (IOException e) { e.printStackTrace(); } } }
Using Java 7 Path
Java 7 introduced the Files utility class where you can write a file using its write method, internally it’s using OutputStream to write byte array into a file.
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class FileWriting { public static void main(String arg[]) { String fileContent = "Hello Java 7 Path"; try { Path path = Paths.get("samplefile.txt"); Files.write(path, fileContent.getBytes()); } catch (IOException e) { e.printStackTrace(); } } }
API in Java 8 Write to File
Where BufferedWriter is used to write text to a character or byte stream. It stores a character in the buffer then prints in bunches.
Here is an example of a Java program to write content to file using Java 8 APIs.
import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class FileWriting { public static void main(String arg[]) { Path path = Paths.get("samplefile.txt"); try (BufferedWriter writer = Files.newBufferedWriter(path)) { writer.write("Hello World !!"); } catch (IOException e) { e.printStackTrace(); } } }
Question: Java writes to file line by line?
Answer: Different-different ways have different methods, here we are sharing some of them.
FileOutputStream
bufferWriter.write("new line"); bufferWriter.newLine();
FileWriter
fileWriter.write("new line");
PrintWriter
printWriter.write("New line");
OutputStreamWriter
osw.write("New line");
Some Important Point when doing java write to file:
- Use try-catch or exception handling to prevent application crash
- Close output stream after use to release all resources.
Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1Java version 11
All How Java write to file are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.|