2012-11-06 6 views
1

그래서 저는 Java-newbie이고 파일을 가지고 놀기 시작했습니다. 필자가 알고있는 타입의 데이터를 담고있는 "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

OK, 이해합니다. 감사합니다 :) – 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

OK, 고맙습니다. – Straightfw

관련 문제