我必須 :-逐行讀取大文本文件。記下每行讀取后的文件指針位置。如果運(yùn)行時(shí)間大于30秒,則停止讀取文件。從新進(jìn)程中的最后一個(gè)文件指針恢復(fù)。我在做什么 :使用RandomAccessFile.getFilePointer()來(lái)記錄文件指針。將RandomAccessFile包裝到另一個(gè)BufferedReader中,以根據(jù)此答案加快文件讀取過(guò)程。當(dāng)時(shí)間大于30秒時(shí),我停止讀取文件。使用新的RandomAccessFile重新啟動(dòng)進(jìn)程并使用RandomAccessFile.seek方法將文件指針移動(dòng)到我離開(kāi)的位置。問(wèn)題:當(dāng)我正在閱讀包裹在RandomAccessFile中的BufferedReader時(shí),似乎文件指針在一次調(diào)用BufferedReader.readLine()時(shí)正在向前移動(dòng)。但是,如果我直接使用RandomAccessFile.readLine(),文件指針正向一步一步正向移動(dòng)。使用BufferedReader作為包裝器: RandomAccessFile randomAccessFile = new RandomAccessFile("mybigfile.txt", "r");BufferedReader brRafReader = new BufferedReader
(new FileReader(randomAccessFile.getFD()));while((line = brRafReader.readLine()) != null) {
System.out.println(line+", Position : "+randomAccessFile.getFilePointer());}輸出:Line goes here, Position : 13040Line goes here, Position : 13040Line goes here, Position : 13040Line goes here, Position : 13040使用Direct RandomAccessFile.readLine RandomAccessFile randomAccessFile = new RandomAccessFile("mybigfile.txt", "r");while((line = randomAccessFile.readLine()) != null) {
System.out.println(line+", Position : "+randomAccessFile.getFilePointer());}輸出:(這是預(yù)期的。每次調(diào)用readline時(shí)文件指針都正常移動(dòng))Line goes here, Position : 11011Line goes here, Position : 11089Line goes here, Position : 12090Line goes here, Position : 13040誰(shuí)能告訴我,我在這做什么錯(cuò)?有什么辦法可以使用RandomAccessFile加快閱讀過(guò)程嗎?
添加回答
舉報(bào)
0/150
提交
取消