我想打開包含UTF-8編碼的文本文件,可以能夠設定位置,閱讀25行,能抽到位置。如何使用FileInputStream和BufferReader實現RandomAccessFile的seek()和getFilePointer()?
不幸的RandomAccessFile不支持UTF-8編碼。所以我寫了這個代碼。我用返回的偏移值遞歸調用getParsedLines()方法讀取下25行,但它打印第1-25行,然後打印349-373,695-719等。
public long getParsedLines(File file, long offset) {
int counter = 0;
FileInputStream fis = null;
InputStreamReader streamReader = null;
BufferedReader br = null;
try {
fis = new FileInputStream(file);
fis.getChannel().position(offset);
streamReader = new InputStreamReader(fis, "UTF8");
br = new BufferedReader(streamReader);
String str;
while (counter <= 24) {
if ((str = br.readLine()) != null) {
System.out.println(str);
} else {
offset = -1;
break;
}
counter++;
}
if (fis != null) {
offset = fis.getChannel().position();
}
} catch (IOException ex) {
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException ex) {
}
}
return offset;
}
?我怎樣才能衝抵了正確的,所以我可以打印1-25,26-50,51-75。 76-100等。
是。對於一些向後兼容性我有一些約束,我要讀的readLine使用()的文本文件「逐行」,並在同一時間不是整個文本只讀25-25線。
你是什麼意思的RandomAccessFile不支持UTF-8? –
@Rocky它沒有任何機制來讀取包含utf-8數據的文件。 –
它沒有readUTF()和writeUTF()方法? –