FileWriter class useful for writing the stream of characters to a file. FileWriter extends from the OutputStreamWriter. For writing streams of bytes, implement the FileOutputStream class. This class has the different constructors to create the instance for the file object.
- FileWriter(File file)– Constructs a FileWriter object given a File object.
- FileWriter(File file, boolean append) – Constructs a FileWriter object given a File object. Appends to the existing file if the append parameter is true. Otherwise overwrites the content.
- FileWriter(FileDescriptor fd) – Constructs a FileWriter object associated with a file descriptor.
- FileWriter(String fileName) – Constructs a FileWriter object given a file name.
- FileWriter(String fileName, boolean append) – Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.
Lets look at the example below to understand how FileWriter class can be implemented.
FileWriterExample.java
<br />package javabeat.net.core;<br /><br />import java.io.File;<br />import java.io.FileWriter;<br />import java.io.IOException;<br /><br />/**<br /><%%KEEPWHITESPACE%%> * Java FileWriter Example<br /><%%KEEPWHITESPACE%%> *<br /><%%KEEPWHITESPACE%%> * @author Krishna<br /><%%KEEPWHITESPACE%%> *<br /><%%KEEPWHITESPACE%%> */<br />public class FileWriterExample {<br /><br /><%%KEEPWHITESPACE%%> /**<br /><%%KEEPWHITESPACE%%> * @param args<br /><%%KEEPWHITESPACE%%> */<br /><%%KEEPWHITESPACE%%> public static void main(String[] args) throws IOException {<br /><br /><%%KEEPWHITESPACE%%> //Create file instance<br /><%%KEEPWHITESPACE%%> File file = new File("NewTextFile.txt");<br /><br /><%%KEEPWHITESPACE%%> //Create FileWriter instance with append flag as false<br /><%%KEEPWHITESPACE%%> FileWriter fileWriter = new FileWriter(file,false);<br /><br /><%%KEEPWHITESPACE%%> //Write string to a file<br /><%%KEEPWHITESPACE%%> fileWriter.write("This is FileWriter Example!!");<br /><br /><%%KEEPWHITESPACE%%> //Write newline character<br /><%%KEEPWHITESPACE%%> fileWriter.write("\n");<br /><br /><%%KEEPWHITESPACE%%> //Write using Offset and length in the string<br /><%%KEEPWHITESPACE%%> fileWriter.write("Whole Text Only Part is Written using Offset and Length",5,20);<br /><br /><%%KEEPWHITESPACE%%> //Close the file writer object<br /><%%KEEPWHITESPACE%%> fileWriter.close();<br /><%%KEEPWHITESPACE%%> }<br /><br />}<br /><br />The new file would have created with the below content if you run the above example program.
NewTextFile.txt<br />This is FileWriter Example!!<br /><%%KEEPWHITESPACE%%> Text Only Part is W<br />