The FileOutputStream
class in Java is used to write raw bytes to a file. It is part of the java.io
package and is typically used for binary data (images, audio, etc.) or writing bytes to text files.
Commonly Used Constructors and Methods

Simple Program
Mahesh wants to write the message "Hello LotusJavaPrince!"
into a file named output.txt
.
import java.io.FileOutputStream; import java.io.IOException; public class FileOutputStreamExample { public static void main(String[] args) { String message = "Hello LotusJavaPrince!"; try (FileOutputStream fos = new FileOutputStream("output.txt")) { fos.write(message.getBytes()); System.out.println("Message written successfully."); } catch (IOException e) { System.out.println("Error: " + e.getMessage()); } } }
Output:
Message written successfully.
Content of output.txt:
Hello LotusJavaPrince!
FileOutputStream
is ideal for writing binary data or raw bytes to files.
- It supports overwriting and appending based on the constructor used.
- For better performance, it can be wrapped with
BufferedOutputStream
. - Always use try-with-resources to handle closing the stream.