我有一个包含大约 100 万行信息的文本文件。鉴于我知道我想要哪条线,并且所有线的长度相等,我正在寻找一种跳转到特定线的方法。
我读到,鉴于所有行都相等,因此不必阅读每一行就可以这样做。如果是这样,任何人都可以提供如何执行此操作的示例代码吗?还是我最好简单地阅读每一行并循环它?
我猜你正在寻找随机文件访问
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);
您是否正在寻找这个:
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;
}
}
编辑:-
从这里:-
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) {}
}
}