使用字节流和缓冲流复处理文件提高读写速度

tech2022-07-15  182

使用字节流和缓冲流复处理文件

@Test public void method() throws IOException { File file1 = new File("test1.png"); File file2 = new File("test2.png"); FileInputStream fileInputStream = new FileInputStream(file1); FileOutputStream fileOutputStream = new FileOutputStream(file2); int len = 0; byte[] bytes = new byte[1024]; while((len = fileInputStream.read(bytes)) != -1){ fileOutputStream.write(bytes,0,len); } System.out.println("复制成功"); fileInputStream.close(); fileOutputStream.close(); }

使用缓冲流提高读写效率

开发中使用缓冲流替换基本流。

@Test public void method() throws IOException { //1.创建文件 File file1 = new File("test1.png"); File file2 = new File("test2.png"); //2.创建流 //2.1创建节点流 FileInputStream fileInputStream = new FileInputStream(file1); FileOutputStream fileOutputStream = new FileOutputStream(file2); //2.2创建缓冲流 BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream); // the number of bytes to write. int len = 0; //每次读的字节数为10 byte[] bytes = new byte[10]; while ((len = bufferedInputStream.read(bytes)) != -1){ //写 bufferedOutputStream.write(bytes,0,len); } System.out.println("复制成功"); //关闭流的顺序,先关闭外层的流,再关闭内层的流 bufferedInputStream.close(); bufferedOutputStream.close(); //fileInputStream.close(); //fileOutputStream.close(); } 注意:先关闭外面的流,在关闭内从的流,实际上在关闭外层流的同时,内层的流也会进行关闭,所以关于内层流的关闭可以省略。实际开发中使用try catch finally 确保关闭流。缓冲流的作用是提高文件的读取和写入速度,提高读写速度的原因是:内部提供了一个缓冲区。
最新回复(0)