有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java内存管理将文件写入内存

我需要将大量文件写入内存,以便多线程快速访问。大约有20个文件,大小从10mb到200mb不等。文件的总大小在内存中约为3Gb。我正在尝试将文件作为字符串存储在地图中

下面是我正在使用的代码。我在输入目录中循环,选择特定的文件,并使用字符串构建来连接文件中的行,因为文件是分隔的,我需要一个字符串

每个文件都包含一个标题行,以>;-我正在使用它为地图创建关键点

星际电车和endram,以及最后的loop,只是为了弄清楚到底发生了什么

private Map<String, String> readFilesIntoMap(File referenceDirectory) throws IOException{
        Map<String, String> refMap = new HashMap<>();

        long startRAM = Runtime.getRuntime().freeMemory();



        for(File refFile : referenceDirectory.listFiles()){
            if(refFile.getName().endsWith(".fa")) {
                BufferedReader br = new BufferedReader(new FileReader(refFile));
                String mapKey = "";
                StringBuilder mapValue = new StringBuilder();

                String currentLine;
                while((currentLine = br.readLine()) != null){
                    if(currentLine.startsWith(">")) mapKey = currentLine.split(" ")[0].substring(1);
                    else mapValue.append(currentLine);
                }

                br.close();

                refMap.put(mapKey, mapValue.toString());

            }
        }

        for(Map.Entry<String, String> entry : refMap.entrySet()){
            System.out.println(entry.getKey() + ": " + entry.getValue().substring(0, 10));
            System.out.println(entry.getValue().getBytes().length);
        }

        long endRAM = Runtime.getRuntime().freeMemory();

        System.out.println(endRAM - startRAM);


        return refMap;
}

代码工作得非常好,并且创建了映射。然而,我的问题是,该程序消耗的内存远远大于文件大小。这些文件加起来是2.9Gb,在峰值时,程序的RAM达到9Gb

我意识到字符串生成器将在RAM中以及存储值的映射中。然而,我看不出RAM是输入信息大小的3倍

有什么想法吗

非常感谢,

萨姆


共 (0) 个答案