缓冲流
BufferedInputStream/BufferedOutputStream
这两个流类为IO提供了带缓冲区的操作,一般打开文件进行写入或读取操作时,都会加上缓冲,这种流模式提高了IO的性能
从应用程序中把输入放入文件,相当于将一缸水倒入到另一个缸子
FileOutputStream--->write方法相当于一滴一滴 地把水转移过去
DataOutputStream--->writeXxx()方法会方便一些,相当于一瓢一瓢把水转移过去
BufferedOutputStream--->write方法更方便,相当于一瓢一瓢先放入桶中,再从桶中倒入到另一个缸中,性能提高了
带缓冲区的拷贝方法
/** * 进行文件的拷贝,利用带缓冲的字节流 * @param srcFile * @param destFile * @throws IOException */ public static void copyFileByBuffer(File srcFile,File destFile) throws IOException { if(!srcFile.exists()) { throw new IllegalArgumentException("文件:"+srcFile+"不存在"); } if(!srcFile.isFile()) { throw new IllegalArgumentException(srcFile + "不是文件"); } BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile)); int c; while((c=bis.read())!=-1) { bos.write(c); bos.flush();//刷新缓冲区,否则写入不到文件中去 } bis.close(); bos.close(); }
单字节文件拷贝
/** * 单字节,不带缓冲进行文件拷贝 * @param srcFile * @param destFile * @throws IOException */ public static void copyFileByByte(File srcFile,File destFile) throws IOException { if(!srcFile.exists()) { throw new IllegalArgumentException("文件:"+srcFile+"不存在"); } if(!srcFile.isFile()) { throw new IllegalArgumentException(srcFile + "不是文件"); } FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(destFile); int c; while((c=in.read())!=-1) { out.write(c); out.flush(); } in.close(); out.close(); }
文件拷贝,字节批量读取
/** * 文件拷贝,字节批量读取 * @param srcFile * @param destFile * @throws IOException */ public static void copyFile(File srcFile,File destFile) throws IOException { if(!srcFile.exists()) { throw new IllegalArgumentException("文件:"+srcFile+"不存在"); } if(!srcFile.isFile()) { throw new IllegalArgumentException(srcFile + "不是文件"); } FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(destFile); byte[] buf =new byte[8*1024]; int b; while((b=in.read(buf,0,buf.length))!=-1) { out.write(buf,0,b); out.flush();//最好jias } in.close(); out.close(); }
测试类
public class IOUtilTest4 { public static void main(String[] args) { try { long start = System.currentTimeMillis(); //IOUtil.copyFileByBuffer(new File("路径"), new File("路径")); //IOUtil.copyFileByByte(new File("路径"), new File("路径")); //最慢 IOUtil.copyFile(new File("路径"), new File("路径"));//效率最快 long end = System.currentTimeMillis(); System.out.println(end - start); } catch (IOException e) { e.printStackTrace(); } } }
浙公网安备 33010602011771号