What's the most efficient way to write large text file in java?

不想你离开。 提交于 2020-01-25 06:55:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!