Java FileWriter write() Method
Example
Write text to a file, and read it back:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Files in Java might be tricky, but it is fun enough!");
myWriter.close();
BufferedReader br = new BufferedReader(new FileReader("filename.txt"));
System.out.println(br.readLine());
br.close();
}
}
Definition and Usage
The write() method writes text to the file. It can write one character, a char array, a String, or a part of an array or a String.
write() does not add a line break. Write "\n" when you want the next text to start on a new line.
Note: If the file already exists, FileWriter replaces its content. To add text to the end of an existing file, open it in append mode: new FileWriter("filename.txt", true).
Syntax
One of the following:
public void write(int c)
public void write(char[] cbuf)
public void write(char[] cbuf, int off, int len)
public void write(String str)
public void write(String str, int off, int len)
Parameter Values
| Parameter | Description |
|---|---|
| c | Optional. The character to write. A char value works here, because it is converted to an int automatically. |
| cbuf | Optional. A char array with the characters to write. |
| str | Optional. The string to write. |
| off | Optional. The position of the first character to write from the array or string. |
| len | Optional. The number of characters to write. |
Technical Details
| Throws: | IOException - if the writer is closed, or if another I/O error occurs. |
|---|
Related Pages
❮ FileWriter Methods