FileOutputStream Class in Java

FileOutputStream creates an OutputStream that you can use to write bytes to a file.
It implements the AutoCloseableCloseable, and Flushable interfaces.
In the previous article, we discussed about Java.io.FileInputStream Class in Java

FileOutputStream Constructors

  • FileOutputStream(File file) - Creates a file output stream to write to the file represented by the specified File object.
  • FileOutputStream(File file, boolean append) - Creates a file output stream to write to the file represented by the specified File object.
  • 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.
- These constructors can throw a FileNotFoundException.
- filePath is the full pathname of a file.
- fileObj is a File object that describes the file. If append is true, the file is opened in append mode.
Creation of a FileOutputStream is not dependent on the file already existing. FileOutputStream will create the file before opening it for output when you create the object. In the case where you attempt to open a read-only file, an exception will be thrown.

FileOutputStream Class API/Methods

  • void close() - Closes this file output stream and releases any system resources associated with this stream.
  • protected void finalize() - 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.
  • FileChannel getChannel() - Returns the unique FileChannel object associated with this file output stream.
  • FileDescriptor getFD() - Returns the file descriptor associated with this stream.
  • void write(byte[] b) - Writes b.length bytes from the specified byte array to this file output stream.
  • void write(byte[] b, int off, int len) - Writes len bytes from the specified byte array starting at offset off to this file output stream.
  • void write(int b) - Writes the specified byte to this file output stream.

FileOutputStream Class Example

The following example creates a sample buffer of bytes by first making a String and then using the getBytes( ) method to extract the byte array equivalent. It then creates three files. The first, file1.txt, will contain every other byte from the sample. The second, file2.txt, will contain the entire set of bytes. The third and last, file3.txt, will contain only the last quarter.
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * The class demonstrate the usage of FileOutputStream class methods.
 * @author javaguides.net
 *
 */
public class FileOutputStreamDemo {
 public static void main(String args[]) {
  String source = "Now is the time for all good men\n" + " to come to the aid of their country\n"
    + " and pay their due taxes.";
  byte buf[] = source.getBytes();
  // Use try-with-resources to close the files.
  try (FileOutputStream f0 = new FileOutputStream("file1.txt");
    FileOutputStream f1 = new FileOutputStream("file2.txt");
    FileOutputStream f2 = new FileOutputStream("file3.txt")) {
   // write to first file
   for (int i = 0; i < buf.length; i += 2)
    f0.write(buf[i]);
   // write to second file
   f1.write(buf);
   // write to third file
   f2.write(buf, buf.length - buf.length / 4, buf.length / 4);
  } catch (IOException e) {
   System.out.println("An I/O Error Occurred");
  }
 }
}

More Examples

Input for below program is:
String content = "This is the text content";
This below program will write the above content to "sample.txt" file
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileOutputStreamExample {
 private static final Logger LOGGER = LoggerFactory
   .getLogger(FileOutputStreamExample.class);

 public static void main(String[] args) {
  File file = new File("sample.txt");
  String content = "This is the text content";

  try (OutputStream fop = new FileOutputStream(file)) {

   // if file doesn't exists, then create it
   if (!file.exists()) {
    file.createNewFile();
   }
   // get the content in bytes
   byte[] contentInBytes = content.getBytes();

   fop.write(contentInBytes);
   System.out.println("Done");

  } catch (IOException e) {
   LOGGER.error(e.getMessage());
  }
 }
}

Reference

Comments