Curriculum
In Java, FileOutputStream is a class that extends the OutputStream class and allows you to write data to a file in the form of bytes. It is used to write data to a file in a byte-by-byte manner, and it is useful for writing binary data, such as images, videos, and audio files. Here is an example of how the FileOutputStream class is used in Java:
import java.io.FileOutputStream;
import java.io.IOException;
public class FileOutputStreamExample {
public static void main(String[] args) {
try {
FileOutputStream fileOutput = new FileOutputStream("example.txt");
String text = "This is an example text.";
byte[] bytes = text.getBytes();
fileOutput.write(bytes);
fileOutput.close();
} catch (IOException e) {
System.out.println("An error occurred while writing to the file: " + e.getMessage());
}
}
}
In this example, we create a FileOutputStream to a file named “example.txt”. We use the write() method to write the bytes of a string to the output stream, and we close the stream using the close() method.
The FileOutputStream class in Java has the following methods:
void write(int b) throws IOException: Writes a byte of data to the file output stream.void write(byte[] b) throws IOException: Writes an array of bytes to the file output stream.void write(byte[] b, int off, int len) throws IOException: Writes a portion of an array of bytes to the file output stream, starting at the specified offset off and writing up to len bytes.void flush() throws IOException: Flushes the file output stream, ensuring that all buffered data is written out to the file.void close() throws IOException: Closes the file output stream and releases any system resources associated with it.Note that some classes that implement the OutputStream class, such as BufferedOutputStream and DataOutputStream, provide additional methods for writing data to the file output stream in a more convenient way. For example, the DataOutputStream class provides methods for writing different types of primitive data types to the file output stream, such as writeInt(int i) and writeDouble(double d).