In this Java tutorial you will learn How to write to a file in Java through a simple example. To write to a file in Java we will use FileWriter and BufferedWriter classes. After reading this Java tutorial you will be able to use OutputStreamWriter on a FileOutputStream classes to write data to a file from Java program.
In this Java tutorial, we will demonstrate how to write to a file in Java with the help of a sample Java program. After going though this tutorial you will be able to use OutputStreamWriter on a FileOutputStream classes to write data to a file from Java program.
To write the Java Write To File we will use two classes FileWriter and BufferedWriter.
FileWriter
FileWriter is a class, which is used for writing character files. The assumptions of constructors about are that the default character encoding and the default byte-buffer size are acceptable. However, in order to specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.
BufferedWriter
The BufferWriter is a class used to write text to a character-output stream, buffering characters in oreder to provide efficiency to write single characters, arrays, and strings.
import java.io.*; class FileWrite { public static void main(String args[]) { try{ // Create file FileWriter fstream = new FileWriter("out.txt"); BufferedWriter out = new BufferedWriter(fstream); out.write("Hello Java"); //Close the output stream out.close(); }catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } } }
If you write the program given above and execute it, this will write "Hello Java" into out.txt file. While creating the object of FileWriter class we have passed the name of the file e.g. "out.txt" as constructor argument.
The BufferedWriter class takes FileWriter object as parameter. The write() method of the BufferedWriter class actually writes the data into the text file.