例如已存在的文件都是双精度浮点数,怎样返回-1,我尝试用FileInputStream
的read()检测是否到了文件结尾,但总是返回输入输出异常,现附上源代码,请
不吝赐教!
创建文件:
import java.io.*;public class Write5000Double {
  public static void main(String[] args) {
    double d;
    try {
      FileOutputStream fos = new FileOutputStream("e:\\temp\\abc");
      DataOutputStream dos = new DataOutputStream(fos);
      for (int i = 0; i < 5000; i++) {
        //double randy=Math.random()*200;
        dos.writeDouble(Math.random() * 200);
      }
      dos.close();
      fos.close();
    }
    catch (IOException x) {
      System.out.println("Caught IOException");
    }
  }
}阅读文件:
import java.io.*;public class Read5000Double2 {
  public static void main(String[] args) {
    try {
      FileInputStream fis = new FileInputStream("f:\\temp\\abc");
      DataInputStream dis = new DataInputStream(fis);
      boolean a = true, readBad = false;
      while (a) {
        int theByte = fis.read();
        double b = dis.readDouble();
      //  System.out.println(theByte);
        if (theByte == -1) {
          a = false;
        }
        if (b < 0 || b > 200) {
          System.out.println("Read bad double:" + b);
        }
      }
      dis.close();
      fis.close();
      if (!readBad) {
        System.out.println("File is valid!");
      }
    }
    catch (IOException x) {
      System.out.println("Caught IOException!");
    }
  }
}运行结果为何总是Caught IOException!

解决方案 »

  1.   

    我知道答案啦
    import java.io.*;public class Read5000Double2 {
      public static void main(String[] args) {
        try {
          FileInputStream fis = new FileInputStream("f:\\temp\\abc");
          DataInputStream dis = new DataInputStream(fis);
          boolean a = true, readBad = false;
          while (a) {
            double b = dis.readDouble();
            if (b == -1) {
              a = false;
            }
            if (b < 0 || b > 200) {
              System.out.println("Read bad double:" + b);
            }
          }
          dis.close();
          fis.close();
          if (!readBad) {
            System.out.println("File is valid!");
          }
        }
        catch (IOException x) {
          System.out.println("Caught IOException!");
        }
      }
    }