我正在尝试使用以下方法编写包含大量数据的文件:
public static <T extends SomeClass> void writeFile(String buffer, Class<T> clazz, int fileNumber) {
String fileType = ".txt";
File file = new File(clazz.getName()+fileNumber+fileType);
PrintWriter printWriter = null;
try {
FileWriter writer = new FileWriter(file);
printWriter = new PrintWriter(writer);
printWriter.print(buffer);//error occurs here
printWriter.flush();
printWriter.close();
System.out.println("created file: "+file.getName());
} catch (IOException e) {
e.printStackTrace();
} finally{
if(printWriter!=null){
printWriter.flush();
printWriter.close();
}
}
System.out.println("Done!");
}
缓冲区字符串包含+ -6mb的数据,当我运行代码时,我在缓冲区中得到一个java.lang.OutOfMemoryError。
答案 0 :(得分:1)
如何用以下内容替换printWriter.print(buffer);
for (int i = 0; i < buffer.length; i += 100) {
int end = i + 100;
if (end >= buffer.length) {
end = buffer.length;
}
printWriter.print(buffer.substring(i, end);
printWriter.flush();
}
答案 1 :(得分:0)
由于6mb不是“数据”,我认为你应该增加你的java VM内存,
看看这里
http://confluence.atlassian.com/display/DOC/Fix+Out+of+Memory+Errors+by+Increasing+Available+Memory