Java FileOutputStream class is a part of java.io package. Today we will look into FileOutputStream class constructors and methods in detail with example codes.
1. Java FileOutputStream
- FileOutputStream is an output stream for writing data to a File or FileDescriptor.
- FileOutputStream is used for writing streams of raw bytes such as image data. It’s good to use with bytes of data that can’t be represented as text such as PDF, excel documents, image files etc.
- FileOutputStream class is a subclass of
OutputStream
class.
2. FileOutputStream Class Hierarchy
3. FileOutputStream Constructors
FileOutputStream provide methods for writing bytes to a file and we can create an instance of FileOutputStream using below constructors.
FileOutputStream(File file)
: Creates a file output stream to write to the file represented by specified file object. If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then aFileNotFoundException
is thrown.FileOutputStream(File file, boolean append)
: Creates a file output stream to write to the file represented by the specified File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning. If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.FileOutputStream (FileDescriptor fdObj)
: Creates a file output stream to write to the specified file descriptor, which represents an existing connection to an actual file in the file system.FileOutputStream (String name)
: Creates a file output stream to write to the file with the specified name.FileOutputStream (String name, boolean append)
: Creates a file output stream to write to the file with the specified name. If the second argument is true, then bytes will be written to the end of the file rather than the beginning. If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason thenFileNotFoundException
is thrown.
4. Java FileOutputStream Methods
Let’s have a look at the below methods of FileOutputStream class.
close()
: This method closes this file output stream and release any system resources associated with the stream.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 reference to it.getChannel()
: This method returns the unique FileChannel object associated with this file output stream. The initial position of the returned channel will be equal to the number of bytes written to the file and writing bytes to this stream will increment the channel’s position.getFD()
: This method returns the FileDescriptor object that represents the connection to the actual file in the file system being used by this FileOutputStream object.write(byte[] b)
: This method writes b.length bytes from the specified byte array to this file output stream.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.write(int b)
: This method writes the specified byte to this file output stream. Implements the write method of OutputStream.
5. Java Write to File using FileOutputStream
package com.journaldev.examples;
import java.io.File;
import java.io.FileOutputStream;
/**
* Java write file using FileOutputStream
*
* @author pankaj
*
*/
public class FileOutputStreamWrite {
public static void main(String[] args) {
File file = null;
FileOutputStream fileOutputStream = null;
String data = "Hello World.";
try {
file = new File("D:/data/file.txt");
fileOutputStream = new FileOutputStream(file);
//create file if not exists
if (!file.exists()) {
file.createNewFile();
}
//fetch bytes from data
byte[] bs = data.getBytes();
fileOutputStream.write(bs);
fileOutputStream.flush();
fileOutputStream.close();
System.out.println("File written successfully.");
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
Java 7 provides try with resource which is a try statement that declares one or more resource. A resource is an object that must be closed after the program is finished with it. The try with resource statement ensures that each resource is closed at the end of the statement. Let’s see how to refactor the above program to use java try with resources.
package com.journaldev.examples;
import java.io.File;
import java.io.FileOutputStream;
/**
* Java write file using FileOutputStream and try with resource
*
* @author pankaj
*
*/
public class FileOutputStreamWriteTrywithResource {
public static void main(String[] args) {
File file = new File("D:/data/file.txt");
String data = "Hello World.";
try (FileOutputStream fileOutputStream = new FileOutputStream(file)){
//create file if not exists
if (!file.exists()) {
file.createNewFile();
}
//fetch bytes from data
byte[] bs = data.getBytes();
fileOutputStream.write(bs);
fileOutputStream.flush();
fileOutputStream.close();
System.out.println("File written successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Also check java write to file and java append to file for more details.
6. Java FileOutputStream Example
Let’s look at some of the methods of FileOutputStream through some example programs.
6.1) finalize()
FileOutputStream finalize() 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 reference to it.
If we try to access FileOutputStream after calling finalize(), we will get an exception.
package com.journaldev.examples;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
/**
* Java FileOutputStream finalize method example
*
* @author pankaj
*
*/
public class FileOutputStreamFinalizeExample extends FileOutputStream{
public FileOutputStreamFinalizeExample(File file) throws FileNotFoundException {
super(file);
}
public static void main(String[] args) {
File file = null;
try {
file = new File("D:/data/file.txt");
FileOutputStreamFinalizeExample fileOutputStream = new FileOutputStreamFinalizeExample(file);
//create file if not exists
if (!file.exists()) {
file.createNewFile();
}
//closing fileOutputStream
fileOutputStream.finalize();
//try to write data
fileOutputStream.write(123);
fileOutputStream.flush();
fileOutputStream.close();
System.out.println("File written successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output of the above program is below:
java.io.IOException: Stream Closed
at java.io.FileOutputStream.write(Native Method)
at java.io.FileOutputStream.write(Unknown Source)
at com.journaldev.examples.FileOutputStreamFinalizeExample.main(FileOutputStreamFinalizeExample.java:31)
6.2) getFD()
FileOutputStream getFD()
method returns the FileDescriptor object that represents the connection to the actual file in the file system being used by this FileOutputStream object.
package com.journaldev.examples;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
/**
* Java FileOutputStream FileDescriptor Example
*
* @author pankaj
*
*/
public class FileOutputStreamFileDescriptorExample {
public static void main(String[] args) {
File file = new File("D:/data/file.txt");
FileDescriptor fileDescriptor = null;
try (FileOutputStream fileOutputStream = new FileOutputStream(file)){
//create file if not exists
if (!file.exists()) {
file.createNewFile();
}
fileDescriptor = fileOutputStream.getFD();
boolean valid = fileDescriptor.valid();
System.out.println("Valid file: "+valid);
} catch (Exception e) {
e.printStackTrace();
}
}
}
6.3) 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.
package com.journaldev.examples;
import java.io.File;
import java.io.FileOutputStream;
/**
* Java write file using FileOutputStream with write(byte[] b, int off, int len) method
*
* @author pankaj
*
*/
public class FileOutputStreamWriteExample {
public static void main(String[] args) {
File file = null;
FileOutputStream fileOutputStream = null;
String data = "Hello World.";
try {
file = new File("D:/data/file.txt");
fileOutputStream = new FileOutputStream(file);
//create file if not exists
if (!file.exists()) {
file.createNewFile();
}
//fetch bytes from data
byte[] bs = data.getBytes();
fileOutputStream.write(bs, 0, 5);//only Hello will be written to a file
fileOutputStream.flush();
fileOutputStream.close();
System.out.println("File written successfully.");
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
That’s all for Java FileOutputStream, I hope nothing important got missed here.
Reference: API Doc