Java FileWriter Example - 3 Ways to Write a File

The java.io.FileWriter is useful to work with characters directly instead of bytes. All the Writer and the Reader classes in Java are treated as Character Streams.

java.io.FileWriter is sub class of OutputStreamWriter which contains the overloaded methods, write(int c), write(char[] c),write(char[] c, int start, int end). These methods help in writing data to a file. Note that here, the method is taking char[] instead of byte[] as in the FileOutputStream (FileOutputStream is a sub-class of OutputStream).


import java.io.FileWriter;
class FileWriterExample
{
public static void main(String args[]) throws Exception
{
// The string to be written
String st="I will be in the file using FileWriter class.";
// Convert st to array
char[] c=st.toCharArray();

// First way
// FileWriter object
FileWriter fw=new FileWriter("output.txt");
// Write the char array
fw.write(c);
// Close FileWriter
fw.close();
// Second way
FileWriter fw1=new FileWriter("output1.txt");
// Write from 0 to end
fw1.write(c,0,c.length);
// Close fw1
fw1.close();
// Third way
FileWriter fw2=new FileWriter("output2.txt");
for(int i=0;i<c.length;i++)
{
fw2.write(c[i]);
}
// Close fw2
fw2.close();
}
}