问题
I'm trying to write a file with some amount of data using this:
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!");
}
The buffer string contains +-6mb of data, and when i run the code i get a java.lang.OutOfMemoryError exactly in buffer.
回答1:
What about replacing printWriter.print(buffer);
with:
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();
}
回答2:
Since 6mb is not so much "data" I think you should increase your java VM memory,
take a look here
http://confluence.atlassian.com/display/DOC/Fix+Out+of+Memory+Errors+by+Increasing+Available+Memory
来源:https://stackoverflow.com/questions/7753424/whats-the-most-efficient-way-to-write-large-text-file-in-java