Java BufferedInputStream,BufferedOutputStream分批快速读取大文件

如果文件太大,一次性读取这个大文件的所有数据,内存可能装不下,但是如果每次只读一个字节数据,会耗时太慢。因此用BufferedInputStream一次读取1024*8个字节数据,用BufferedOutputStream放入缓冲区,分批读写。代码如下:

public static void main(String[] args) throws IOException
{
    BufferedInputStream bufferInput = null;
    BufferedOutputStream bufferOutput = null;
    try
    {
        // 输入缓冲流
        InputStream input = new FileInputStream(new File("c:\\100MB.txt"));
        bufferInput = new BufferedInputStream(input);
        // 输出缓冲流
        OutputStream output = new FileOutputStream(new File("c:\\100MB_test.txt"));
        bufferOutput = new BufferedOutputStream(output);
        // 定义个8kb字节数组,作为缓冲区流
        byte[] bytes = new byte[1024 * 8];
        int len = 0;
        while((len = bufferInput.read(bytes)) != -1)
        {
            bufferOutput.write(bytes, 0, len);
        }
    }
    catch(IOException e)
    {
    }
    finally
    {
        try
        {
            if(bufferInput != null)
            {
                bufferInput.close();
            }
            if(bufferOutput != null)
            {
                bufferOutput.close();
            }
        }
        catch(IOException e)
        {
        }
    }
} 

版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。