处理从文本文件中读取的字符串时,内存使用效率低下

时间:2017-02-10 11:41:45

标签: java string garbage-collection heap

我有一个大文件 - 约1.7 GB - 包含2500万行,每行代码如下:text,number。

事情是文本可以在多行中相同,即

我是个男孩,34岁

..

...

我是个男孩,56岁

我在while循环中读取文件的每一行,并将字符串和数字放在一个hashmap中。

代码:

InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("filename.txt");

InputStreamReader stream = new InputStreamReader(is, StandardCharsets.UTF_8);

BufferedReader reader = new BufferedReader(stream);

while(true)
{
    line =reader.readLine();
    if (line == null) 
    {
        break;
    }
    String text= line.substring(0, line.lastIndexOf(",")).trim();

    String id = line.substring(line.lastIndexOf(",") + 1).trim();

    hm.put(text,id);
}

其中hm是一个hashmap。

我使用子字符串 lastIndexOf 的原因是因为文本本身可能有逗号。

我的问题是:我使用太多字符串吗?从文本文件中提取的重复字符串是作为副本保留在内存中还是仅存在其中一个。有没有办法(使用字符串或其他内容的方法)来减少使用的字符串数。当我使用Eclipse MAT分析内存使用时,它显示大约9 GB的堆空间使用。

0 个答案:

没有答案