用Java编写大型文本文件的最有效方法是什么? [英] What's the most efficient way to write large text file in java?

查看:70
本文介绍了用Java编写大型文本文件的最有效方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下方法写入包含一些数据的文件:

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!");
}

缓冲区字符串包含+ -6mb的数据,当我运行代码时,我恰好在缓冲区中收到java.lang.OutOfMemoryError.

The buffer string contains +-6mb of data, and when i run the code i get a java.lang.OutOfMemoryError exactly in buffer.

推荐答案

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编写大型文本文件的最有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆