我在写个project~关于词典方面的,需要读入数据(数据大小约27M),然后我用bufferedReader将数据每行转成字符串存在String[]数组里~~~~当我调试程序的时候就出现了如题的错误。搜索了下相关知识,虽然可以调heap space初始大小,但终究不是解决问题的根本途径(别人电脑上的初始值还是没变啊~~)请问大家应该如何处理,我这样读入数据的方式怎样做可以更好一些??(因为为了即时性(速度),所以读入到String数组中,而不是每次查词都打开文件、读入文件再进行搜索。)
请大家赐教~~感激不尽~~~~~~~~~~~~~~~~~~~~~~~~~~下附出错的相关源代码:这是我用于读取文件的类public class Location {
private String[] s;
private int num_line = 0;
private int real_start = 0; //前面声明的行数
//(最终real_start对应的值即为第一行有用数据在s数组中的下标)

//初始化File中的每一行字符串,并存入s数组中
public Location(File f) throws IOException {
//统计行数
BufferedReader br = new BufferedReader(new FileReader(f));
while(br.readLine() != null) {
++num_line;
}
br.close();
//存入到s数组中
br = new BufferedReader(new FileReader(f));
s = new String[num_line+1];
int cnt = 0; // 当前处理的行
while((s[cnt] = br.readLine()) != null) {
if(s[cnt].startsWith("  ")) {
++real_start;
}
++cnt;
}
br.close();
}
在另一个类中连续调用Location从而读入数据(总计约27M)public void init() throws IOException{
index_noun = new Location(new File("./dict/index.noun"));
index_verb = new Location(new File("./dict/index.verb"));
index_adj = new Location(new File("./dict/index.adj"));
index_adv = new Location(new File("./dict/index.adv"));
data_noun = new Location(new File("./dict/data.noun"));
data_verb = new Location(new File("./dict/data.verb"));
data_adj = new Location(new File("./dict/data.adj"));
data_adv = new Location(new File("./dict/data.adv"));
lex_file = new Location(new File("./dict/lex_file.txt"));
}

解决方案 »

  1.   

     private String[] s;
    建议不用String数组存
    用List吧,应该不会存在OOM问题,同时不需要确定行数~
      

  2.   

    如果文件的内容不需要保存到缓存中,那我建议处理完的数据就释放掉String s = "";
    while((s = br.readLine()) != null)    {
                if(s.startsWith("  "))    {
                    ++real_start;
                }
                ++cnt;
            }如果文件的内容需要保存到缓存中,那我建议不要用String[],而改用StringBuffer[]。因为new 一个String在缓存中是定长的,而StringBuffer则是变长的。用StringBuffer[]会节省缓存空间。
    以上希望等对你有所帮助。
      

  3.   

    如果不确定行数请问String[]的大小应该怎么开?我的版本是1.6的~~
      

  4.   


    用StringBuffer怎么读~毕竟readline的返回值是String~是说将所有的字符串都改成Stringbuffer么?
      

  5.   


    StringBuffer strB = new StringBuffer();
    strB.append("");
      

  6.   

    我也是用Java读写,文件大小达400MB之多,时间只要70多秒。
    给你个建议:用XML来来读写和保存你的文件。
      

  7.   

    看代码你内存溢出的原因是String[]的对象集过多,堆空间不足尝试减少输入文件的数量,如果发现读入量减少仍然内存不足,那很有可能有内存泄漏,看你的文件读写流有没有正常关闭并释放内存