我有一個包含大約100萬行信息的文本文件。鑑於我知道我想要哪條線,並且所有線條的長度相等,我正在尋找一種方法來跳轉到特定線條。跳轉到.txt文件中的特定行,其中所有行的長度都等於Java
我讀過,有可能這樣做,而不必每行都讀一行,因爲所有行都相等。如果是這樣,任何人都可以提供一個示例代碼,我該如何做到這一點?或者,我最好簡單地閱讀每一行並循環播放它?
我有一個包含大約100萬行信息的文本文件。鑑於我知道我想要哪條線,並且所有線條的長度相等,我正在尋找一種方法來跳轉到特定線條。跳轉到.txt文件中的特定行,其中所有行的長度都等於Java
我讀過,有可能這樣做,而不必每行都讀一行,因爲所有行都相等。如果是這樣,任何人都可以提供一個示例代碼,我該如何做到這一點?或者,我最好簡單地閱讀每一行並循環播放它?
您正在尋找這樣的:
String line = FileUtils.readLines(file).get(lineNumber);
,或者你可以嘗試使用迭代器,像這樣: -
LineIterator l= IOUtils.lineIterator(new BufferedReader(new FileReader("file.txt")));
for (int lineNumber = 0; l.hasNext(); lineNumber++) {
String line = (String) l.next();
if (lineNumber == desiredLineNumber) {
return line;
}
}
編輯: -
從here: -
int sizeofrecordinbytes = 290;
// for this example this is 1 based, not zero based
int recordIWantToStartAt = 12400;
int totalRecordsIWant = 1000;
File myfile = new File("someGiantFile.txt");
// where to seek to
long seekToByte = (recordIWantToStartAt == 1 ? 0 : ((recordIWantToStartAt-1) * sizeofrecordinbytes));
// byte the reader will jump to once we know where to go
long startAtByte = 0;
// seek to that position using a RandomAccessFile
try {
// NOTE since we are using fixed length records, you could actually skip this
// and just use our seekToByte as the value for the BufferedReader.skip() call below
RandomAccessFile rand = new RandomAccessFile(myfile,"r");
rand.seek(seekToByte);
startAtByte = rand.getFilePointer();
rand.close();
} catch(IOException e) {
// do something
}
// Do it using the BufferedReader
BufferedReader reader = null;
try {
// lets fire up a buffered reader and skip right to that spot.
reader = new BufferedReader(new FileReader(myfile));
reader.skip(startAtByte);
String line;
long totalRead = 0;
char[] buffer = new char[sizeofrecordinbytes];
while(totalRead < totalRecordsIWant && (-1 != reader.read(buffer, 0, sizeofrecordinbytes))) {
System.out.println(new String(buffer));
totalRead++;
}
} catch(Exception e) {
// handle this
} finally {
if (reader != null) {
try {reader.close();} catch(Exception ignore) {}
}
}
這仍然讀取每行 –
@JeroenVannevel:是的,但我已經給出了第一個解決方案,如果OP知道行號,那麼我們可以使用String line = FileUtils.readLines(file).get(lineNumber); (如果我錯了,請糾正我的錯誤!!) –
我同意這是一種方便的方法,但它仍會先讀取文件的每一行(這與OP所要求的相反)。 –
I gue SS你正在尋找一個隨機文件訪問
File file = ...;
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
int lineNumber = ...; // first line number is 0
int lineWidth = ...; // your fixed line width
long beginIndexOfLine = lineWidth * lineNumber;
randomAccessFile.seek(beginIndexOfLine);
byte[] line = new byte[lineWidth];
randomAccessFile.read(line);
僅當行(text)是單字節字符時,纔在'RandomAccessFile = lineWidth * lineNumber'中查找指針,否則,我們必須考慮'char - > bytes'轉換中的字符編碼。 –
謝謝,是的,我正在尋找這樣的事情。但是,如何檢查我的線寬?它是基於每行字符數或字節數?我正在使用ASCII編碼。 –
@ChrystleSoh因爲,所有的行都是相同的寬度,只需讀取第一行(使用例如'BufferedReader')並轉換爲字節長度'(string.getBytes(「char encoding」).length)'並將其存儲爲常量某處。 –
如果你知道以字節爲單位線路長度,你可以使用'SeekableByteChannel':http://docs.oracle.com/javase/tutorial/essential/io/ rafs.html –