Java - File Input Output PushbackInputStream

Introduction

PushbackInputStream lets you unread bytes using its unread() method.

There are three versions of the unread() method.

read() method will first read the bytes being unreaded.

The following code how to use the PushbackInputStream to unread bytes to the input stream and reread them.

Demo

import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PushbackInputStream;

public class Main {
  public static void main(String[] args) {
    String srcFile = "Main.java";

    try (PushbackInputStream pis = new PushbackInputStream(new FileInputStream(
        srcFile))) {/*  www.j av a2  s. co  m*/
      // Read one byte at a time and display it
      byte byteData;
      while ((byteData = (byte) pis.read()) != -1) {
        System.out.print((char) byteData);

        // Unread the last byte that we have just read
        pis.unread(byteData);

        // Reread the byte we unread (or pushed back)
        byteData = (byte) pis.read();
        System.out.print((char) byteData);
      }
    } catch (FileNotFoundException e1) {
      FileUtil.printFileNotFoundMsg(srcFile);
    } catch (IOException e2) {
      e2.printStackTrace();
    }
  }
}

class FileUtil {
  // Prints the location details of a file
  public static void printFileNotFoundMsg(String fileName) {
    String workingDir = System.getProperty("user.dir");
    System.out.println("Could not find the file '" + fileName + "' in '"
        + workingDir + "' directory ");
  }

  // Closes a Closeable resource such as an input/output stream
  public static void close(Closeable resource) {
    if (resource != null) {
      try {
        resource.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}

Result