我有 wiki.txt 文件,其大小为 50 MB。
我需要对文件执行几项操作,因此我认为就性能而言最好的方法是将文件加载到内存中,对吗?
这是我编写的代码:
File file = new File("wiki.txt"); FileInputStream fileInputStream = new FileInputStream(file); FileChannel fileChannel = fileInputStream.getChannel(); MappedByteBuffer mapByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, file.length()); System.out.println((char)mapByteBuffer.get());
我在这段代码上遇到错误:mapByteBuffer.get()
。
我尝试了 get() 函数的几个选项,但所有选项都出现错误,甚至在 e.getMessage() 上都没有出现错误,我只是得到了 null。
另一个需要注意的重要事项,我的文本文件包含我需要执行的英文单词和操作,如果表达存在于该文本文件中,则进行搜索。
谢谢。
最佳答案
我建议使用 MemoryMappedFile 直接从磁盘读取文件,而不是将其加载到内存中。
RandomAccessFile file = new RandomAccessFile("wiki.txt", "r");
FileChannel channel = file.getChannel();
MappedByteBuffer buf = channel.map(FileChannel.MapMode.READ_WRITE, 0, 1024*50);
然后你就可以像往常一样读取缓冲区了。
关于java - 在Java中将文本文件加载到内存中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8500935/