我正在尝试使用以下方法编写包含一定量数据的文件:
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();
}
关于java - 在java中编写大型文本文件最有效的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7753424/