2011-10-13 86 views
0

我想用这个来写数据的一定量的文件:在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准确在缓冲区中。

+0

您是否使用-Xmx命令行选项向Java VM提供了合理的内存量? –

+0

您是否尝试使用较小的块而不是单个调用来编写缓冲区? – millimoose

+0

顺便说一句,我相信PrintWriter.write使用内存的原因是它将整个字符串编码为一个字节数组,然后写入它。 –

回答

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(); 
} 
+2

程序员现在习惯于拥有这么多的记忆,他们从来没有考虑过保存它。生活就是平衡。 – Thom

+0

@Thom:同意你的看法,但平衡意味着你以正确的方式使用最大资源。 ;) –

+1

平衡就是用正确的方式使用适量的资源。 – Thom

相关问题