Java I/O Byte Streams

Byte Streams Overview

  • Programs use byte streams to perform input and output of 8-bit bytes.
  • All byte stream classes are descended from InputStream and OutputStream.

Byte stream classes

java.io.InputStream (implements java.io.Closeable)
java.io.OutputStream (implements java.io.Closeable, java.io.Flushable)
To demonstrate how byte streams work, we'll focus on the file I/O byte streams, FileInputStream and FileOutputStream. Other kinds of byte streams are used in much the same way; they differ mainly in the way they are constructed.

Using Byte Streams

We'll explore FileInputStream and FileOutputStream with examples, which uses byte streams to copy sample.txt, one byte at a time.

FileOutputStream Example

package com.javaguides.javaio.fileoperations.examples;

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("C:/Project_Work/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());
  }
 }
}
The above example spends most of its time in a simple loop that reads the input stream and writes the output stream, one byte at a time.

Read more about FileOutputStream here.

FileInputStream Example

package com.javaguides.javaio.fileoperations.examples;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class FileInputStreamExample {
 public static void main(String[] args) {
  File file = new File("C:/Project_Work/sample.txt");
  try (FileInputStream fis = new FileInputStream(file)) {
   int content;
   while ((content = fis.read()) != -1) {
    // convert to char and display it
    System.out.print((char) content);
   }
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}
Observe the above example, it is reading one byte at a time.

Read more about FileInputStream here.

ByteArrayOutputStream and ByteArrayInputStream Example

The example of these two classes is demonstrated in below articles.

Always Close Streams

  • Closing a stream when it's no longer needed is very important — so important that the above examples use a try with resource statement to guarantee that both streams will be closed even if an error occurs. This practice helps avoid serious resource leaks.
  • Close the stream either using finally block or try with resource statement as shown in the example.

When Not to Use Byte Streams

FileOutputStreamExample seems like a normal program, but it actually represents a kind of low-level I/O that you should avoid. Since sample.txt contains character data, the best approach is to use Character Streams. There are also streams for more complicated data types. Byte streams should only be used for the most primitive I/O.

Read related top posts on Java I/O Guide

Comments