How to Write text to File in Java
This tutorial show you how to write text to File using java. We can write text to a file in a couple of ways. First we explore the old way using a BufferedWriter
. Next we evaluate the try-with-resources way of java 7. Finally we’ll show you how to write text to File using only one line of code.
Write text to File (Old way)
First lets explore the old way of creating a file. As noted this is uses the most lines of code. We create a BufferedWriter
which takes a OutputStreamWriter
which takes a FileOutputStream
. Once the writer is initialized we write some random string to the file. After we write we close the writer.
package com.memorynotfound.file;
import java.io.*;
public class WriteToFile {
public static void main(String... args){
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("foo.txt"), "utf-8"));
writer.write("Write to file java");
} catch (IOException ex) {
ex.printStackTrace(System.err);
} finally {
try {
if (writer != null){
writer.close();
}
} catch (Exception ex) {
/*ignore*/
}
}
}
}
Write text to File (try-with-resources)
Since java 7 we can initielize using try-with-resources. Since we use try-with-resources, the JVM will handle the closing and flushing of our writer.
package com.memorynotfound.file;
import java.io.*;
public class WriteToFileTryResource {
public static void main(String... args) throws IOException {
try (Writer writer = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream("foo.txt"), "utf-8"))) {
writer.write("Write to file java");
}
}
}
Write text to File (Only one line!)
To finish since java 7 we can also create a file using the Files.write()
method. Simple and just one line of code!
package com.memorynotfound.file;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class WriteToFileFiles {
public static void main(String... args){
try {
Files.write(Paths.get("/tmp/foo.txt"), "Hello, World!".getBytes());
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
}