[英]read until specific index in a file with RandomAccessFile java
我試圖使用RandomAccessFile從兩個特定索引之間的文件中讀取。
我知道我可以使用seek()
函數跳轉到索引,但是在找到特定索引之前,我找不到如何從文件中讀取文本的答案。
例如,我有一個巨大的文件,我想從索引100到索引500讀取文本,我將這樣開始:
public String get_text(){
raf.seek(100) //raf= my RandomAccessFile
String txt=raf.read(500) //read until index 500 which i don't know how to do
return txt;
}
請幫我 :)
這是我解決問題的方式:
try {
int index = 100;
raf.seek(index); //index = 100
int counter = 0;
int length = 400;
while (counter < length) { //want to read the characters 400 times
char c = (char) raf.read();
if (!(c == '\n')) { //don't append the newline character to my result
sb.append(c); //sb is a StringBuilder
counter++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
我還看到了另一種解決方案,其中readFully()與字節數組一起使用,效果也很好。
try {
raf.seek(index);
byte[] bytes = raf.readFully(new byte[(int) length]); //length of the charactersequence to be read
String str = bytes.toString();
} catch (IOException e){
e.printStackTrace();
}
在此解決方案中,必須在換行符內考慮字節數組的長度,因此您必須考慮行長來進行計算。 ->在文件中以換行符開始,在文件中以換行符結束。 長度= endInFile-startInFile +1;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.