检查输入是否已完成

时间:2012-11-06 19:28:42

标签: java

所以我是一个Java新手并开始玩文件。假设我有一些文件“tes.t”包含我知道的类型的数据 - 假设它们是int-double-int-double等等。我不知道里面这样的对的数量 - 我怎样才能确保输入完成?就我目前的知识而言,我想到了这样的事情:

try{
        DataInputStream reading = new DataInputStream(new FileInputStream("tes.t"));
        while(true)
        {
            System.out.println(reading.readInt());
            System.out.println(reading.readDouble());
        }
        }catch(IOException xxx){}
}

然而,这种无限循环让我感到不舒服。我的意思是 - 我想IOException应该在输入完成后立即流行,但我不确定这是否是一个好方法。有没有更好的方法来做到这一点?或者更确切地说 - 什么是一种更好的方法,因为我确信我的不好:)

4 个答案:

答案 0 :(得分:3)

由于您的文件具有双重对,因此可以执行以下操作:

DataInputStream dis = null;
try {
    dis = new DataInputStream(new FileInputStream("tes.t"));
    int i = -1;
    // readInt() returns -1 if end of file...
    while ((i=dis.readInt()) != -1) {
        System.out.println(i);
        // since int is read, it must have double also..
        System.out.println(dis.readDouble());
    }

} catch (EOFException e) {
    // do nothing, EOF reached

} catch (IOException e) {
    // handle it

} finally {
    if (dis != null) {
        try {
            dis.close();

        } catch (IOException e) {
             // handle it
        }
    }
}

答案 1 :(得分:2)

您可以执行以下操作:

try{
  FileInputStream fstream = new FileInputStream("tes.t");
  DataInputStream in = new DataInputStream(fstream);
  BufferedReader br = new BufferedReader(new InputStreamReader(in));
  String strLine;
  //Read File Line By Line
  while ((strLine = br.readLine()) != null)   {
  System.out.println (strLine);
  }
  //Close the input stream
  in.close();
  }catch (IOException e){//Catch exception if any
 System.err.println("Error: " + e.getMessage());
 }

注意:此代码未经测试。

答案 2 :(得分:1)

这是来自javadoc:

  

抛出:EOFException - 如果此输入流到达之前的结尾   读四个字节。

这意味着您可以抓住EOFException以确保已达到EOF。您还可以添加某种应用程序级别标记,以显示文件已完全读取。

答案 3 :(得分:0)

这个怎么样:

DataInputStream dis = null;
try {
    dis = new DataInputStream(new FileInputStream("tes.t"));
    while (true) {
        System.out.println(dis.readInt());
        System.out.println(dis.readDouble());
    }

} catch (EOFException e) {
    // do nothing, EOF reached

} catch (IOException e) {
    // handle it

} finally {
    if (dis != null) {
        try {
            dis.close();

        } catch (IOException e) {
            // handle it
        }
    }
}