集册 Java实例教程 文件读取保存测验

文件读取保存测验

欢马劈雪     最近更新时间:2020-01-02 10:19:05

502
将前400个质数作为整数写入到名为400primes.dat的文件中。

import java.io.BufferedInputStream;/*来自 时代Java公众号 - nowjava.com*/

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();

    read();

  }


  public static boolean isPrime(int checkNumber) {

    double root = Math.sqrt(checkNumber);
    /*
    来 自*
     n o w j a   v  a . c o m - 时  代  Java
    */

    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 = 
展开阅读全文