2012-11-06 146 views
1

所以我是一个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应该在输入完成后立即着手,但我不确定这是否是一个好的方法。有没有更好的方法来做到这一点?或者说 - 什么是一个更好的办法,因为我敢肯定,我的是不好的:)

+0

尝试http://docs.oracle.com/javase/ tutorial/essential/io/bytestreams.html –

+0

无限循环会以100%CPU使用率挂起程序。 –

回答

3

由于您的文件有INT-两对,你可以做如下:

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 
     } 
    } 
} 
+0

好的,我明白了。谢谢:) – Straightfw

+0

哦,但还有一个问题......如果在输入中使用了-1作为合适的int,该怎么办?那么它会不会错误地忽略while循环,并且仍然有一些输入需要处理? – Straightfw

1

这是从的javadoc:

抛出:EOFException - 如果此输入流 阅读前四到达终点字节。

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

+0

我明白了。谢谢:) – Straightfw

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

注:此代码是未经测试。

+0

我明白了。谢谢:) – Straightfw

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 
     } 
    } 
} 
+0

好的,谢谢:) – Straightfw