2013-03-19 2 views
0

Java에서 FileInputStream을 사용하여 한 번에 청크를 읽음으로써 파일을 읽으려고합니다. 코드는 다음입니다 :파일을 읽는 동안 실행 및 디버그에서 다른 출력이 발생합니다.

 File file = new File(filepath); 
     FileInputStream is = new FileInputStream(file); 
     byte[] chunk = new byte[bytelength]; 
     int chunkLen = chunk.length; 
     long lineCnt = 0; 

     while ((chunkLen = is.read(chunk)) != -1) { 

      String decoded = getchunkString(chunk); 
      System.out.println(decoded); 

      System.out.println("---------------------------------"); 

     } 

내가 ByteLength가 = 128을 복용하고 다음과 같이 작은 파일을 테스트하기 위해 노력하고 있습니다 : 나는 코드를 실행할 때

graph G{ 
biz -- mai 
biz -- ded 
biz -- ronpepsi 
blaine -- dan 
dan -- graysky 
dan -- iancr 
dan -- maxwell 
dan -- foursquare 
blaine -- neb 
} 

는이 같은 청크를 읽

graph G{ 
biz -- mai 
biz -- ded 
biz -- ronpepsi 
blaine -- dan 
dan -- graysky 
dan -- iancr 
dan -- maxwell 
dan -- foursquare 
blaine 
--------------------------------- 
-- neb 
} 
iz -- mai 
biz -- ded 
biz -- ronpepsi 
blaine -- dan 
dan -- graysky 
dan -- iancr 
dan -- maxwell 
dan -- foursquare 
blaine 
--------------------------------- 

두 번째 청크가 어떻게되는지 모르겠습니까? 나는 그것이 있어야 희망 만

내가 is.read(chunk) 10 다음되고 -1은 첫 번째 덩어리를 인쇄 debugg
-- neb 
    } 

.

+0

, 당신은 ... –

답변

1

버퍼에 가비지 데이터가 포함될 수 있으므로 읽을 때까지 최대 바이트 수 (예 : chunkLen) 만 사용해야합니다.

while ((chunkLen = is.read(chunk)) != -1) { 
    for (int i = 0; i < chunkLen; i++){ 
    //read the bytes here 
    } 
} 

또는 당신은 당신은 그에 따라 코드를 수정해야

while ((chunkLen = is.read(chunk)) != -1) { 
    String decoded = new String(chunk, 0, chunkLen); 
    System.out.println(decoded); 
    System.out.println("---------------------------------"); 
} 

아래로 문자열 생성자를 사용할 수 있습니다. 텍스트 파일을 읽는 경우

+0

매우 U 감사 (BufferedReader로에 싸여)을 FileReader를 사용할 수 있습니다 그것은 당신을 위해 일 경우 답을 받아 들여야 –

+0

을했다 : –

+0

실제로 내가 청크를 삭제하고 괜찮 았는데 .. –

관련 문제