Java FileOutputStream

www.‮itfigi‬dea.com

FileOutputStream is a class in Java that is used for writing data to a file as a stream of bytes. It is a subclass of OutputStream, which is an abstract class that provides a standard way of writing data to different destinations in the form of bytes.

Here's an example of using the FileOutputStream class to write data to a file:

import java.io.*;

public class FileOutputStreamExample {
    public static void main(String[] args) {
        try {
            FileOutputStream output = new FileOutputStream("file.txt");
            String message = "Hello, world!";
            byte[] data = message.getBytes();
            output.write(data);
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, we create a FileOutputStream object and pass the name of the file we want to write to as a parameter. We then convert a string message to a byte array using the getBytes method and write the data to the file using the write method of the FileOutputStream object.

It's important to note that the write method of the FileOutputStream class writes a single byte at a time, so it is not very efficient when writing large amounts of data. To write data more efficiently, you can use the BufferedOutputStream class, which writes data to an internal buffer and provides methods for writing data in larger chunks.

Overall, the FileOutputStream class provides a flexible and efficient way of writing data to a file in Java. By using the various methods provided by FileOutputStream, you can write data to files in a variety of different ways depending on your specific needs.