我想用这个来写数据的一定量的文件:在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准确在缓冲区中。
您是否使用-Xmx命令行选项向Java VM提供了合理的内存量? –
您是否尝试使用较小的块而不是单个调用来编写缓冲区? – millimoose
顺便说一句,我相信PrintWriter.write使用内存的原因是它将整个字符串编码为一个字节数组,然后写入它。 –