如JAVA API
FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeInt(12345);
oos.writeObject("Today");
oos.writeObject(new Date()); oos.close();我按照上面的方法Write object但是收到的是:
java.lang.OutOfMemoryError: Java heap sapce
下面的是我的代码。我写的对象挺大的,当异常出现时,本地写了一个40MB+的文件,对于这个问题,大家有没有什么解决方法?对于这种特大的文件,一般的处理方法是什么?
public static boolean WriteObject(Object object,String filename){
System.gc();
if(object instanceof Serializable){
FileOutputStream fos;
try {
fos = new FileOutputStream(filename);
} catch (FileNotFoundException e1) {
System.err.println("Can not find file:"+filename+".");
return false;
}
            ObjectOutputStream oos;
try {
oos = new ObjectOutputStream(fos);

oos.writeObject(object);
oos.close();
} catch (IOException e) {
e.printStackTrace();
System.err.println("Can not write object:"+filename+".");
return false;
}
return true;
}
else{
System.err.println("Object "+ object.getClass()+" can not be save.");
return false;
} }

解决方案 »

  1.   

    你可以在外围套个BufferedWriter试试:
    oos = new ObjectOutputStream(fos);               
    ------>
    oos=new ObjectOutputStream(new BufferedOutputStream(fos));不知道行不行,试试吧
      

  2.   

    虚拟机默认好像是64M你写了40多M,加上虚拟机本身,加上各种类各种对象和垃圾回收器,差不多溢出了。你设置下虚拟机内存大小吧,具体我忘记了。。好像是runasapplication 里面的config,填入参数
      

  3.   


    解决方法:调用ObjectOutputStream的reset方法,丢弃缓存中已发送过的对象如下事例用到流控的思想:丢弃缓存中已发送的对象。。将文件1写入到文件2... File csvFile = new File("文件1");
    File objFile = new File("文件2");
    int recInterval = 10000;

    try {
    Date start = new Date();
    System.out.println(start + ": started with interval " + recInterval);

    int count = 0;
    BufferedReader bufRdr = new BufferedReader(
    new FileReader(csvFile));
    ObjectOutputStream oos = new ObjectOutputStream(
    new FileOutputStream(objFile));
    String line;
    while( (line = bufRdr.readLine()) != null) {
    String [] cols = line.split(",");
    // oos.writeUnshared(cols);
    oos.writeObject(cols);
    ++count;
    if (count % recInterval == 0)
    oos.reset();
    }
    bufRdr.close();
    oos.close();

    Date finish = new Date();
    System.out.println(finish + ": finished for " + count + " records");
      System.out.println("Execution time (ms): " + (finish.getTime() - start.getTime()));
      System.out.println();
    }
    catch (Exception ex) {
    ex.printStackTrace();
    }
      

  4.   

    4楼:您的方法不行,我写的是一个对象,每一次写入之后都.close();1楼:我的类是序列化过的,但是类中包括其它的类,会不会是每一个类也都要序列化?
       通过减少数据,我的结果能写入到本地。所以,主要问题是文件太大。
    2楼:我试一试你的方法
    3楼:我不知道你具体设置的方法是什么,但我在eclipse -->run-->run configure 里面设置了 Arguments -Xmx1024m 谢谢各位关注。
      

  5.   

    http://www.iteye.com/problems/21351lz看看这里的方法 你试试看
      

  6.   

    改下jvm的内存大小,也可以分开写入,一次不要写的那么多!
      

  7.   

    解决了吗?没的话看看这个:
    http://okone96.itpub.net/post/9033/328376