[英]What's the most efficient way to write large text file in java?
我正在嘗試使用以下方法寫入包含一些數據的文件:
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。
如何替換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();
}
由於6mb並不是很多“數據”,我認為您應該增加Java VM內存,
在這里看看
http://confluence.atlassian.com/display/DOC/Fix+Out+of+Memory+Errors+by+Increeasing+Available+Memory
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.