Java FileOutputStream write() Method
Example
Write an array of bytes and one more byte to a file, then read the file:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
FileOutputStream output = new FileOutputStream("filename.txt");
output.write("Hello World".getBytes());
output.write('!');
output.close();
Scanner reader = new Scanner(new File("filename.txt"));
System.out.println(reader.nextLine());
reader.close();
}
}
Definition and Usage
The write() method writes bytes (raw data) to the file.
It can write one byte, a whole byte array, or a part of an array. To write text, first change it to bytes with the getBytes() method of String.
Note: new FileOutputStream("filename.txt") replaces the old content of the file. Use new FileOutputStream("filename.txt", true) to add to the end of the file instead.
Syntax
One of the following:
public void write(int b)
public void write(byte[] b)
public void write(byte[] b, int off, int len)
Parameter Values
| Parameter | Description |
|---|---|
| b | Required. The byte to write (as an int), or a byte array with the bytes to write. |
| off | Optional. The index of the first byte in the array to write. |
| len | Optional. The number of bytes to write from the array. |
Technical Details
| Throws: | IOException - if the stream is closed, or if the bytes cannot be written. |
|---|
Related Pages
Java FileOutputStream Tutorial
❮ FileOutputStream Methods