How to Write to a File in Java - Methods Explained
Learn how to write to a file in Java using three popular methods: FileOutputStream()
, FileWriter.write()
, and Files.write()
. Each method offers different capabilities for file handling in Java applications.
Write To File in Java
There are multiple ways to write to a file in Java. Below are the three most popular methods:
- Using
FileOutputStream()
constructor - Using
FileWriter.write()
method - Using
Files.write()
method
Write To File Using FileOutputStream Constructor
FileOutputStream
is used to create a file and write data into it. If the file doesn’t exist, it will be created before opening it for output.
Syntax
The following constructor takes a file name as a string to create an output stream object:
Syntax
OutputStream f = new FileOutputStream("C:/java/hello.txt");
The following constructor takes a file object to create an output stream:
Syntax
File f = new File("C:/java/hello.txt");
OutputStream f = new FileOutputStream(f);
for (int x = 0; x < bWrite.length; x++) {
os.write(bWrite[x]); // writes the bytes
}
Example: Write To File Using FileOutputStream Constructor
The following example demonstrates writing to a file using FileOutputStream
:
Example
package com.example;
import java.io.*;
public class FileTest {
public static void main(String[] args) {
try {
byte bWrite[] = {65, 66, 67, 68, 69};
OutputStream os = new FileOutputStream("output.txt");
for (int x = 0; x < bWrite.length; x++) {
os.write(bWrite[x]);
}
os.close();
InputStream is = new FileInputStream("output.txt");
int size = is.available();
for (int i = 0; i < size; i++) {
System.out.print((char) is.read() + " ");
}
is.close();
} catch (IOException e) {
System.out.print("Exception");
}
}
}
Output
A B C D E
Write To File Using FileWriter.write() Method
The FileWriter.write()
method allows writing characters to a file.
Syntax
Below is a simple example to write data to a file:
Syntax
// Get an existing file
File file = new File("D:/test/testFile1.txt");
// Write content
FileWriter writer = new FileWriter(file);
writer.write("Sample data");
writer.close();
Example: Write To File Using FileWriter.write() Method
The following example demonstrates how to write to a file using FileWriter.write()
:
Example
package com.example;
import java.io.*;
public class FileTest {
public static void main(String[] args) {
try {
File file = new File("D:/test/testFile1.txt");
// Create the file
if (file.createNewFile()) {
System.out.println("File is created!");
} else {
System.out.println("File already exists.");
}
// Write content
FileWriter writer = new FileWriter(file);
writer.write("Sample data");
writer.close();
// Read content
FileReader reader = new FileReader(file);
int c;
while ((c = reader.read()) != -1) {
System.out.print((char) c);
}
} catch (IOException e) {
System.out.print("Exception");
}
}
}
Output
File is created!
Sample data
Write To File Using Files.write() Method
Files.write()
is a newer and more flexible method to create and write to a file in one command.
Syntax
Below is an example to write data to a file using Files.write()
:
Syntax
String data = "Sample data";
Files.write(Paths.get("D:/test/testFile3.txt"), data.getBytes());
List lines = Arrays.asList("First line", "Second line");
Files.write(Paths.get("file6.txt"), lines, StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
Example: Write To File Using Files.write() Method
The following example demonstrates writing to a file using Files.write()
:
Example
package com.example;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
public class FileTest {
public static void main(String[] args) {
try {
String data = "Sample data";
Files.write(Paths.get("D:/test/testFile3.txt"), data.getBytes());
List lines = Arrays.asList("First line", "Second line");
Files.write(Paths.get("file6.txt"), lines, StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
List content = Files.readAllLines(Paths.get("D:/test/testFile3.txt"));
System.out.println(content);
content = Files.readAllLines(Paths.get("file6.txt"));
System.out.println(content);
} catch (IOException e) {
System.out.print("Exception");
}
}
}
Output
[Sample data]
[First line, Second line]