gpt4 book ai didi

java - 如何在 Java 中创建和访问索引以进入大文件的特定位置

转载 作者:行者123 更新时间:2023-12-01 20:57:26 26 4
gpt4 key购买 nike

我有一个大文件,格式如下:

唯一字符串 \t 信息

在我的程序中,我需要读取此文件以通过唯一字符串键获取信息。由于性能很重要,我无法每次都读取每一行来查找 key ,而且我无法将文件加载到内存中,因为它太重了。然后我只想读取该文件一次,然后使用 String 键和该文件在文件中的位置(以字节为单位)构建索引。该索引类似于 HashMap,其键是唯一字符串,值是文件中键出现的字节。

似乎 RandomAccessFile 可以做到这一点,但我不知道如何做到。

那么,如何构建这个索引,然后通过这个索引访问特定行呢?

最佳答案

我建议的方法是读取文件并跟踪位置。将沿途的位置存储在 map 中,以便您以后查找。

第一种方法是将您的文件用作DataInput,并使用RandomAccessFile#readline

RandomAccessFile raf = new RandomAccessFile("filename.txt", "r");
Map<String, Long> index = new HashMap<>();

现在,您的数据是如何存储的?如果是逐行存储的,并且编码符合DataInput标准,那么就可以使用。

long start = raf.getFilePointer();
String line = raf.readLine();
String key = extractKeyFromLine(line);
index.put(key, start);

现在,您可以随时返回并获取数据。

long position = index.get(key);
raf.seek(position);
String line = raf.readLine();

这是一个完整的示例:

package helloworld;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.HashMap;
import java.util.Map;

/**
* Created by matt on 07/02/2017.
*/
public class IndexedFileAccess {
static String getKey(String line){
return line.split(":")[0];
}
public static void main(String[] args) throws IOException {
Map<String, Long> index = new HashMap<>();
RandomAccessFile file = new RandomAccessFile("junk.txt", "r");
//populate index and read file.
String s;
do{
long start = file.getFilePointer();
s = file.readLine();
if(s!=null){
String key = getKey(s);
index.put(key, start);
}
}while(s!=null);

for(String key: index.keySet()){
System.out.printf("key %s has a pos of %s\n", key, index.get(key));
file.seek(index.get(key));
System.out.println(file.readLine());
}
file.close();

}
}

junk.txt 包含:

dog:1, 2, 3cat:4, 5, 6zebra: p, z, t

最后的输出是:

key zebra has a pos of 24zebra: p, z, tkey cat has a pos of 12cat:4, 5, 6key dog has a pos of 0dog:1, 2, 3

对此有很多注意事项。例如,如果您需要更强大的编码,那么当您第一次阅读它时,您将需要创建一个可以管理编码的阅读器,并仅使用您的 RandomAccessFile 作为输入流。如果行太大,readLine() 方法将会失败。然后,您必须设计自己的策略来提取 key /数据对。

关于java - 如何在 Java 中创建和访问索引以进入大文件的特定位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42077102/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com