日期:2014-05-20  浏览次数:20812 次

BufferedReader问题
Java code

            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("c:/temp")));
            String line = null;
            while ((line = br.readLine()) != null) {
                this.jTextArea1.append(line);
                this.jTextArea1.append("\n");
            }
            br.close();


请问上面这段代码 读取文件放到TextArea上面的操作,文件稍大,就会内存溢出,
BufferedReader是如何对内存进行操作的?

改用FileChannel 和 MappedByteBuffer就不会产生该问题,请问各位为什么呀?

------解决方案--------------------
又试了下,选了temp文件大小是11213650 bytes

Java code

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import javax.swing.JTextArea;

public class Test {
    
    public static void main(String[] args) throws InterruptedException {
        long startFreeMemory = Runtime.getRuntime().freeMemory();
        System.out.println("start free memory is: " + startFreeMemory);
        try {
            new Test().go1();
            
            long endFreeMemory = Runtime.getRuntime().freeMemory();
            System.out.println("end free memory is: " + endFreeMemory);
        } catch (Exception e) {
            long endFreeMemory = Runtime.getRuntime().freeMemory();
            System.out.println("end free memory is: " + endFreeMemory);
            
            e.printStackTrace();
        }

    }
    
    public void go1() throws Exception {
        FileChannel fChannel = new RandomAccessFile("temp", "r").getChannel();
        MappedByteBuffer mByteBuffer = fChannel.map(FileChannel.MapMode.READ_ONLY, 0, fChannel.size());
        Charset charset = Charset.forName("iso-8859-1");
        CharsetDecoder decoder = charset.newDecoder();
        CharBuffer charBuffer = CharBuffer.allocate(1024);
        charBuffer = decoder.decode(mByteBuffer);
        JTextArea jta = new JTextArea();
        System.out.println("set text length = " + new String(charBuffer.array(), 0, charBuffer.limit()).length());
        
        jta.setText(new String(charBuffer.array(), 0, charBuffer.limit()));
        fChannel.close();
    }
    
    public void go2() throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("temp")));
        String line = null;
        JTextArea jta = new JTextArea();
        while ((line = br.readLine()) != null) {
            jta.append(line);
            System.out.println(line);
            jta.append("\n");
        }
        br.close();

    }
}