Writing Binary Streams - Java File Path IO

Java examples for File Path IO:File Stream

Introduction

To write data to a binary file, you use the following classes:

FileOutputStream connects to a File object and creates an output stream that can write to the file.

BufferedOutputStream connects to a FileOutput Stream and adds output buffering.

DataOutputStream can write primitive data types and strings to a stream.

Creating a DataOutputStream object requires nested constructors.

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class Main {
  public static void main(String[] args) throws FileNotFoundException {
    File file = new File("name");
    DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
  }
}

If you prefer, you can unravel the constructors like this:

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class Main {
  public static void main(String[] args) throws FileNotFoundException {
    File file = new File("name");
    FileOutputStream fos = new FileOutputStream(file);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    DataOutputStream out = new DataOutputStream(bos);
  }
}

FileOutputStream class has an optional boolean parameter you can use to indicate that the file should be appended if it exists.

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class Main {
  public static void main(String[] args) throws FileNotFoundException {
    File file = new File("name");

    DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file, true)));
  }
}

Related Tutorials