Java FileWriter Example - 3 Ways to Write a File

The is useful to work with characters directly instead of bytes. All the Writer and the Reader classes in Java are treated as Character Streams. 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).

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
// Close FileWriter
// Second way
FileWriter fw1=new FileWriter("output1.txt");
// Write from 0 to end
// Close fw1
// Third way
FileWriter fw2=new FileWriter("output2.txt");
for(int i=0;i<c.length;i++)
// Close fw2

Posted by at on

Tags: Java IO,