File Read Save Quiz - Java File Path IO

Java examples for File Path IO:Binary File

Introduction

Write the first 400 prime numbers as integers to a file called 400primes.dat.

Read the integers from this file and displays them.

Demo Code

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {
  public static void main(String[] arguments) {
    write();/*from   w w  w.  ja  v  a  2s.c  om*/
    read();
  }

  public static boolean isPrime(int checkNumber) {
    double root = Math.sqrt(checkNumber);
    for (int i = 2; i <= root; i++) {
      if (checkNumber % i == 0)
        return false;
    }
    return true;
  }

  private static void write() {
    int[] primes = new int[400];
    int numPrimes = 0;
    int candidate = 2;
    while (numPrimes < 400) {
      if (isPrime(candidate)) {
        primes[numPrimes] = candidate;
        numPrimes++;
      }
      candidate++;
    }

    try (
    FileOutputStream file = new FileOutputStream("400primes.dat");
        BufferedOutputStream buff = new BufferedOutputStream(file);
        DataOutputStream data = new DataOutputStream(buff);) {

      for (int i = 0; i < 400; i++)
        data.writeInt(primes[i]);
      data.close();
    } catch (IOException e) {
      System.out.println("Error -- " + e.toString());
    }
  }

  public static void read() {
    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());
    }
  }
}

Result


Related Tutorials