gpt4 book ai didi

java - 在Java中将文本文件加载到内存

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:15:22 25 4
gpt4 key购买 nike

我有 wiki.txt 文件,它的大小是 50 MB。

  1. 我需要对文件做几件事,所以我认为就性能而言最好的方法是将文件加载到内存中,对吗?

  2. 这是我写的代码:

    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/

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