0

我创建了一个随机访问文件,并在其中写入了一些信息。我想将随机访问文件中每一行的位置存储在一个数组中。我将有一个指向随机访问文件每一行的索引。所以我需要在我的索引中存储随机访问文件行的位置。

我的程序如下

package randomaccessfile;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class raf {

   public static void main(String[] args) throws FileNotFoundException, IOException {
      File file = new File("DocumentsFile.txt");
      RandomAccessFile raf = new RandomAccessFile(file, "rw");
      for (int i = 0; i <= 10 ; i++) {
         String sentence = "1 Info Name Surname"; //i create sentences in the random access file
         raf.seek(file.length());
         raf.writeBytes(sentence);
         raf.writeBytes("\r\n");
      }
      raf.close();
   }
}

对于在随机访问文件中创建的每一行,我想将它们的位置存储在一个数组中。

然后这些位置将存储在索引中。

有什么方法可以用来返回随机访问文件中一行的位置吗?

4

3 回答 3

5

RandomAccessFile已经提供了你想要的一切。

一方面,您不需要seek()在这里:文件指针前进超过每次写入操作时写入文件的字节。

这意味着,在你写完 line 之后n,对于 的任何值,从对象n中获取的结果都会给你 line 的起始偏移量。第 1 行从偏移量 0 开始,这几乎是您在这里真正需要考虑的唯一事情。.getFilePointer()RandomAccessFilen+1

于 2011-12-23T22:09:50.467 回答
0

另一方面,如果您真正关心的是行号,您可以使用 LineNumberReader 将写入文件中的每一行映射到给定的行号。

File file = new File("jedi.txt");

try(LineNumberReader lnr = new LineNumberReader(new FileReader(file))){
    String line = null;

    while ( (line = lnr.readLine()) != null){
        System.out.println(lnr.getLineNumber() + " " + line );
    }
}catch(IOException e){
    e.printStackTrace();
}

当然,这与 RandomAccessFiles 无关,但它可能是一种替代方法,具体取决于您在做什么。

于 2011-12-23T22:31:35.677 回答
0

您可以使用临时变量来存储最后一个 FilePointer。如果必须反转 readline,您可以使用此变量设置阅读器指针。

RandomAccessFile myReader = new RandomAccessFile(fileObject, "r");    
long current_postion = myReader.getFilePointer();
myReader.readLine();
if (line should be reversed){
   myReader.seek(current_postion); //Point to the previous line
}
于 2021-10-27T14:52:27.313 回答