[英]Memory Mapped File location
我正在尝试搜索 268 000 个单词的列表。 这个想法是检查用户输入的单词是否存在于该列表中。 我使用简单的 I/O stream 完成了此操作,但搜索大约需要 5 秒,这太长了。 我的文件当前位于资产中。 我一直在寻找更有效的方法来搜索我的文件,并且遇到了 Memory 映射缓冲区。 但是,我不清楚在以下示例中我应该将文件存储在哪里:
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class ReadFiles {
private static String largeFile = "sowpods.txt";
public static void read() throws IOException {
File file = new File(largeFile);
FileChannel fileChannel = new
RandomAccessFile(file,"r").getChannel();
MappedByteBuffer buffer = fileChannel.map(
FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());
System.out.println(buffer.isLoaded());
System.out.println(buffer.capacity());
}
}
如果我将它留在资产中,我该如何读取它? 目前,我收到“sowpods.txt:打开失败:ENOENT(没有这样的文件或目录)”错误消息。 感谢您的任何提示!
在这里使用内存映射文件不是一个好主意。 您实质上是在浪费OS资源,无论如何它不会使您获得最佳速度。
如果您只是偶尔执行一次搜索,则想保持简单,又不想在两次搜索之间将文件保留在内存中,请使用BufferedInputStream。 给它一个10 kB的缓冲区,它应该可以非常快地执行,并且很可能会使磁盘饱和。
如果执行大量搜索,请尝试在两次搜索之间将内容保留在内存中。 使用HashSet或TreeSet。 如果您使用的是HashSet,请为其提供足够的存储桶。
如果这都不适合您(例如,内存不足,您有数百万个单词,并且仍需要快速搜索),请将这些单词转换为某些SQL数据库,将数据放在表中并为其建立索引。 这确实是数据库擅长的。 您可以轻松找到适合自己目的的数据库。
显然,300k个单词不是很多,它应该很容易地装入内存中,大约10 MB。 根据您的使用场景,您可能还需要查看Bloom filter 。
这是一个例子。
/** Memory-map the model file in Assets. */
private MappedByteBuffer loadModelFile(Activity activity) throws IOException {
AssetFileDescriptor fileDescriptor = activity.getAssets().openFd(getModelPath());
FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor());
FileChannel fileChannel = inputStream.getChannel();
long startOffset = fileDescriptor.getStartOffset();
long declaredLength = fileDescriptor.getDeclaredLength();
return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength);
}
@Override
protected String getModelPath() {
// you can download this file from
// see build.gradle for where to obtain this file. It should be auto
// downloaded into assets.
return "mobilenet_v1_1.0_224.tflite";
}
mobil.net_v1_1.0_224.tflite
文件粘贴在资产中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.