跳转到.txt文件中的特定行,其中所有行在Java中的长度相等

时间:2013-09-21 13:36:09

标签: java file-io

我有一个包含大约100万行信息的文本文件。我正在寻找一种跳转到特定线的方法,因为我知道我想要哪条线,并且所有线的长度相等。

我读到,只要所有行都相等,就可以这样做,而不必阅读每一行。如果是这样,任何人都可以提供一个示例代码,我该怎么做?或者我最好只是阅读每一行并循环它?

2 个答案:

答案 0 :(得分:1)

我猜您正在寻找随机文件访问

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);

答案 1 :(得分:0)

你在找这个:

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) {}
    }
}
相关问题