转自:
Java中如何使用BufferedInputStream,BufferedOutputStream分批快速读取大文件呢?
下文讲述使用BufferedInputStream,BufferedOutputStream读取大文件的示例分享,如下所示:
当文件过大时,如果一次性读取内存中,可能出现内存不足的情况
此时我们需要分批读写数据的方式,按批将数据读出和写入
下文将使用代码的方式讲述具体的实现方法,如下所示
例:
public static void main(String[] args) throws IOException { BufferedInputStream bufferInput = null; BufferedOutputStream bufferOutput = null; try { // 输入缓冲流 InputStream input = new FileInputStream(new File("D:\\200MB.txt")); bufferInput = new BufferedInputStream(input); // 输出缓冲流 OutputStream output = new FileOutputStream(new File("D:\\200MB_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) { } } }