Java FileWriter Class
The FileWriter class inherits from the OutputStreamWriter class. This class writes data to the stream character by character. You can create the required objects through 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 which data is to be written.
- append: If the append parameter is true, bytes are written to the end of the file, equivalent to appending information. If the append parameter is false, bytes are written to 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 value indicating whether to append data.
FileWriter(String fileName, boolean append)
After successfully creating a FileWriter object, you can refer to the methods in the following list to operate on the file.
| Serial number | Method description |
|---|---|
| 1 |
public void write(int c) throws IOException Writes a single character c. |
| 2 |
public void write(char [] c, int offset, int len) Writes a portion of a character array, starting at offset and having length len. |
| 3 |
public void write(String s, int offset, int len) Writes a portion of a string, starting at offset and having length len. |
Example
Example
import java.io.*;
public class FileRead {
public static void main(String args[]) throws IOException {
File file = new File("Hello1.txt");
//Create file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
//Write content to file
writer.write("This\n is\n an\n example\n");
writer.flush();
writer.close();
//Create a FileReader object
FileReader fr = new FileReader(file);
char[] a = new char[50];
fr.read(a); //Read content from array
for (char c : a)
System.out.print(c); //Print characters one by one
fr.close();
}
}
The compilation and running result of the above example is as follows:
This is an example
Other extensions
Java Streams