Java BufferedWriter write() Method
Example
Write a string, a character and another string to a file, and read the text back:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter("filename.txt"));
bw.write("Hello");
bw.write(' ');
bw.write("World");
bw.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 writer. 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. Use the newLine() method to start 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
❮ BufferedWriter Methods