2013-03-19 22 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 
--------------------------------- 

我不明白第二塊是怎麼來的?我希望它應該是唯一的

-- neb 
    } 

當我debugg is.read(chunk)變爲10,然後-1,只會打印第一個塊。

+0

如果你正在閱讀的文本文件,你可以使用的FileReader(裹在BufferedReader類) – 2013-03-19 05:54:21

回答

1

有可能緩衝區可能包含垃圾數據,所以你只需要使用字節只能讀取字節,即chunkLen你的情況。

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

,或者您可以使用String構造如下

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

需要相應地修改代碼。

+0

感謝ü非常..它的工作 – 2013-03-19 08:47:29

+0

你應該接受的答案,如果它的工作對你:) – 2013-03-19 08:49:00

+0

其實我清除塊,它工作得很好.. – 2013-03-19 09:52:46

相關問題