开发者

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

开发者 https://www.devze.com 2023-04-12 14:11 出处:网络
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) {

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()+fi开发者_C百科leNumber+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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号