Java FileOutputStream
📂 Java FileOutputStream
FileOutputStream is a byte stream class used to write raw byte data to a file.
It is mainly used for binary files like images, videos, or any non-text files, but can also write text files.
-
Package:
java.io -
Superclass:
OutputStream
✅ Syntax
🔹 1. Writing Bytes to a File
-
Converts string to bytes using
getBytes(). -
Automatically overwrites the file if it already exists.
🔹 2. Appending Data to a File
By default, FileOutputStream overwrites the file.
To append, pass true as the second argument:
🔹 3. Writing Binary Data (Images, Audio, etc.)
-
Useful for writing images, audio, videos, and other binary files.
🔹 4. Copy File Using FileInputStream & FileOutputStream
-
Reads source file bytes and writes them to destination file.
-
Efficient for large files using a buffer.
🔹 5. Important Methods
| Method | Description |
|---|---|
write(int b) |
Writes one byte to file |
write(byte[] b) |
Writes byte array to file |
write(byte[] b, int off, int len) |
Writes subset of byte array |
close() |
Closes the stream and releases resources |
flush() |
Forces all data to be written immediately |
✅ Best Practices
-
Use try-with-resources to automatically close streams.
-
Use buffers for large files (combine with
BufferedOutputStream). -
Handle
IOExceptionproperly.
Summary
-
FileOutputStream= byte stream for output -
Can overwrite or append files
-
Works with binary and text files
-
Often used with
FileInputStreamto copy files
