Java 使用带缓冲的字节流读写、拷贝数据
使用带缓冲的字节流可以提高读写速度。
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class ReadByBufferedByteStream { public static void main(String[] args) { try { FileInputStream fis=new FileInputStream("movie.mp4"); BufferedInputStream bis=new BufferedInputStream(fis,5000000); FileOutputStream fos=new FileOutputStream("movie_copy.mp4"); BufferedOutputStream bos=new BufferedOutputStream(fos,5000000); byte input[]=new byte[1000000]; int count=0; long before=System.currentTimeMillis(); while(bis.read(input)!=-1) { count++; bos.write(input); } bos.close(); fos.close(); bis.close(); fis.close(); System.out.println("总共用时"+(System.currentTimeMillis()-before)+"毫秒"); System.out.println("读取了"+count+"次"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
输出:
总共用时138毫秒 读取了42次