Java FileWriter Class
The FileWriter class inherits from the OutputStreamWriter class. This class writes character data to a stream. You can create the required objects using the following constructors.
Constructs a FileWriter object given a File object.
FileWriter(File file)
Constructs a FileWriter object given a File object.
FileWriter(File file, boolean append)
Parameters:
- file: The File object to write data to.
- append: If the append parameter is true, bytes are written to the end of the file, effectively appending information. If the append parameter is false, data is written at the beginning of the file.
Constructs a FileWriter object associated with a file descriptor.
FileWriter(FileDescriptor fd)
Constructs a FileWriter object given a file name with a boolean indicating whether to append the data.
FileWriter(String fileName, boolean append)
After successfully creating a FileWriter object, you can manipulate the file using the methods listed below.
No. | Method Description |
---|---|
1 | public void write(int c) throws IOException <br> Writes a single character c. |
2 | public void write(char [] c, int offset, int len) <br> Writes a portion of an array of characters starting at offset and of length len. |
3 | public void write(String s, int offset, int len) <br> Writes a portion of a string starting at offset and of length len. |
Example
import java.io.*;
public class FileRead {
public static void main(String args[]) throws IOException {
File file = new File("Hello1.txt");
// Creates the file
file.createNewFile();
// Creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes content to the file
writer.write("This\n is\n an\n example\n");
writer.flush();
writer.close();
// Creates a FileReader object
FileReader fr = new FileReader(file);
char[] a = new char[50];
fr.read(a); // Reads content into array
for (char c : a)
System.out.print(c); // Prints characters one by one
fr.close();
}
}
The above example compiles and runs with the following output:
This
is
an
example