Read int from a file with buffer in Java

Description

The following code shows how to read int from a file with buffer.

You should always wrap your OutputStream with a BufferedOutputStream for better performance. The BufferedOutputStream class has two constructors that accept an OutputStream.

Example


//from   w ww  .  j  a  va 2 s  .  c om

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.IOException;

public class Main {
  public static void main(String[] arguments) {
    try {
      FileInputStream file = new FileInputStream("400primes.dat");
      BufferedInputStream buff = new BufferedInputStream(file);
      DataInputStream data = new DataInputStream(buff);

      try {
        while (true) {
          int in = data.readInt();
          System.out.print(in + " ");
        }
      } catch (EOFException eof) {
        buff.close();
      }
    } catch (IOException e) {
      System.out.println("Error - " + e.toString());
    }
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    I/O »




Binary File
Byte Array
CharSet
Checksum
Console
Create Copy Move Delete
Directory
Drive
Encode Decode
File Attribute
File Lock
File System
GZIP
Jar File
NIO Buffer
Path
Scanner
StreamTokenizer
Temporary File
Text File
Zip