
- Java.io - Home
- Java.io - BufferedInputStream
- Java.io - BufferedOutputStream
- Java.io - BufferedReader
- Java.io - BufferedWriter
- Java.io - ByteArrayInputStream
- Java.io - ByteArrayOutputStream
- Java.io - CharArrayReader
- Java.io - CharArrayWriter
- Java.io - Console
- Java.io - DataInputStream
- Java.io - DataOutputStream
- Java.io - File
- Java.io - FileDescriptor
- Java.io - FileInputStream
- Java.io - FileOutputStream
- Java.io - FilePermission
- Java.io - FileReader
- Java.io - FileWriter
- Java.io - FilterInputStream
- Java.io - FilterOutputStream
- Java.io - FilterReader
- Java.io - FilterWriter
- Java.io - InputStream
- Java.io - InputStreamReader
- Java.io - LineNumberInputStream
- Java.io - LineNumberReader
- Java.io - ObjectInputStream
- Java.io - ObjectInputStream.GetField
- Java.io - ObjectOutputStream
- io - ObjectOutputStream.PutField
- Java.io - ObjectStreamClass
- Java.io - ObjectStreamField
- Java.io - OutputStream
- Java.io - OutputStreamWriter
- Java.io - PipedInputStream
- Java.io - PipedOutputStream
- Java.io - PipedReader
- Java.io - PipedWriter
- Java.io - PrintStream
- Java.io - PrintWriter
- Java.io - PushbackInputStream
- Java.io - PushbackReader
- Java.io - RandomAccessFile
- Java.io - Reader
- Java.io - SequenceInputStream
- Java.io - SerializablePermission
- Java.io - StreamTokenizer
- Java.io - StringBufferInputStream
- Java.io - StringReader
- Java.io - StringWriter
- Java.io - Writer
- Java.io package Useful Resources
- Java.io - Discussion
Java - FileOutputStream Class
Introduction
The Java.io.FileOutputStream class is an output stream for writing data to a File or to a FileDescriptor. Following are the important points about FileOutputStream −
This class is meant for writing streams of raw bytes such as image data.
For writing streams of characters, use FileWriter.
Class declaration
Following is the declaration for Java.io.FileOutputStream class −
public class FileOutputStream extends OutputStream
Class constructors
Sr.No. | Constructor & Description |
---|---|
1 |
FileOutputStream(File file) This creates a file output stream to write to the file represented by the specified File object. |
2 |
FileOutputStream(File file, boolean append) This creates a file output stream to write to the file represented by the specified File object. |
3 |
FileOutputStream(FileDescriptor fdObj) This creates an output file stream to write to the specified file descriptor, which represents an existing connection to an actual file in the file system. |
4 |
FileOutputStream(String name) This creates an output file stream to write to the file with the specified name. |
5 |
FileOutputStream(String name, boolean append) This creates an output file stream to write to the file with the specified name. |
Class methods
Sr.No. | Method & Description |
---|---|
1 |
void close()
This method closes this file output stream and releases any system resources associated with this stream. |
2 |
protected void finalize()
This method cleans up the connection to the file, and ensures that the close method of this file output stream is called when there are no more references to this stream. |
3 |
FileChannel getChannel()
This method returns the unique FileChannel object associated with this file output stream. |
4 |
FileDescriptor getFD()
This method returns the file descriptor associated with this stream. |
5 |
void write(byte[] b)
This method writes b.length bytes from the specified byte array to this file output stream. |
6 |
void write(byte[] b, int off, int len)
This method writes len bytes from the specified byte array starting at offset off to this file output stream. |
7 |
void write(int b)
This method writes the specified byte to this file output stream. |
Methods inherited
This class inherits methods from the following classes −
- Java.io.OutputStream
- Java.io.Object
Example - Closing FileOutputStream After Writing
The following example shows the usage of Java FileOutputStream close() method. This example demonstrates how to manually close a FileOutputStream after writing data to a file.
FileOutputStreamDemo.java
package com.tutorialspoint; import java.io.FileOutputStream; import java.io.IOException; public class FileOutputStreamDemo { public static void main(String[] args) { FileOutputStream fos = null; try { // Open a file output stream fos = new FileOutputStream("output.txt"); // Write some data to the file String data = "Hello, World!"; fos.write(data.getBytes()); System.out.println("Data written successfully."); } catch (IOException e) { e.printStackTrace(); } finally { // Close the FileOutputStream in the finally block to ensure closure try { if (fos != null) { fos.close(); System.out.println("FileOutputStream closed successfully."); } } catch (IOException e) { e.printStackTrace(); } } } }
Output
Let us compile and run the above program, this will produce the following result−
Data written successfully. FileOutputStream closed successfully.
Explanation
A FileOutputStream is created for "output.txt".
The string "Hello, World!" is converted into bytes and written to the file.
The close() method is called inside a finally block to ensure that the file is always closed, even if an exception occurs.
Checking if (fos != null) prevents a NullPointerException in case the file wasn't successfully opened.
Example - Using finalize() to Close a FileOutputStream
The following example shows the usage of Java FileOutputStream finalize() method.
FileOutputStreamDemo.java
package com.tutorialspoint; import java.io.FileOutputStream; import java.io.IOException; public class FileOutputStreamDemo { static class CustomFileOutputStream extends FileOutputStream { public CustomFileOutputStream(String fileName) throws IOException { super(fileName); } @Override protected void finalize() throws Throwable { System.out.println("Finalize method called. Closing FileOutputStream."); this.close(); // Explicitly closing the file output stream super.finalize(); } } public static void main(String[] args) throws IOException { CustomFileOutputStream fos = new CustomFileOutputStream("output.txt"); fos.write("Hello, World!".getBytes()); // Making object eligible for garbage collection fos = null; // Requesting garbage collection System.gc(); System.out.println("Garbage Collection Requested."); } }
Output
Let us compile and run the above program, this will produce the following result−
Garbage Collection Requested. Finalize method called. Closing FileOutputStream.
Explanation
A custom class CustomFileOutputStream extends FileOutputStream and overrides finalize().
In finalize(), we print a message and explicitly close the file stream.
The fos object is set to null, making it eligible for garbage collection.
System.gc() requests garbage collection (though execution is not guaranteed immediately).
When garbage collection occurs, finalize() gets called, ensuring the file stream is closed.
Example - Writing Data to a File Using FileChannel
The following example shows the usage of Java FileOutputStream getChannel() method.
FileOutputStreamDemo.java
package com.tutorialspoint; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class FileOutputStreamDemo { public static void main(String[] args) { try (FileOutputStream fos = new FileOutputStream("output.txt")) { // Get FileChannel from FileOutputStream FileChannel fileChannel = fos.getChannel(); // Create a ByteBuffer with data ByteBuffer buffer = ByteBuffer.allocate(64); buffer.put("Hello, FileChannel!".getBytes()); // Flip the buffer to prepare for writing buffer.flip(); // Write buffer contents to the file fileChannel.write(buffer); System.out.println("Data written to file using FileChannel."); } catch (IOException e) { e.printStackTrace(); } } }
Output
Let us compile and run the above program, this will produce the following result−
Data written to file using FileChannel.
Explanation
A FileOutputStream object is created for output.txt.
The getChannel() method is used to get the FileChannel.
A ByteBuffer is created, filled with data, and flipped to prepare for writing.
The buffer is written to the file using fileChannel.write(buffer).
The try-with-resources statement ensures the file stream is closed properly.