62,612
社区成员
发帖
与我相关
我的任务
分享
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;
}
}
解决方法:调用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();
}