1.拷贝文件的四种方式:
第一种:直接操作,每次操作一个字节,操作效率非常低
FileInputStream fis = new FileInputStream("123.jpg" ); FileOutputStream fos = new FileOutputStream("789.jpg" ); int b ; while ((b = fis.read())!= -1){ fos.write(b); } fis.close(); fos.close(); 第二种:定义byte数组,长度正好等于输入流的字节总数,弊端是拷贝大数据时会出现内存溢出. //第二种拷贝,定义byte数组,每次输入所有字节数, avlianble FileInputStream fis = new FileInputStream("123.jpg" ); FileOutputStream fos = new FileOutputStream("1020.jpg" ); byte [] arr = new byte [fis.available()] ; int b ; while ((b = fis.read(arr))!= -1) { fos.write(arr); } fis.close(); fos.close(); 第三种:定义小数组,这种方法推荐使用,综合效率比较高. FileInputStream fis = new FileInputStream("致青春.avi" ); FileOutputStream fos = new FileOutputStream("copy.avi" ); byte [] arr = new byte [1024*8] ; int b ; while((b = fis.read(arr))!= -1) { fos.write(arr); } fis.close(); fos.close(); } 第四种:使用Buffered缓冲来操作,其实其底层还是用到的byte数组,而且长度也是8192,跟第三种一样.开发也推荐这个 注意: 第一:使用Buffered的时候,方法的参数列表跟的是IO流对象的子类对象(即要操作的文件封装成的对象,如下括号红色所示) 第二:用Buffered的时候,一定不能忘了bis.clos()和bos.close()或bis.flush()和bos.flush() close和flush方法的区别: 两者都具备刷新功能,将缓冲区里的字节全部刷新到文件中. close方法刷新完之后就不能写了. flush刷新完之后可以继续写. flush在网络编程,例如QQ聊天的案例.聊天的文件先写到缓冲区,但是聊天需要时时刷新,这时候就要用flush方法.如果用了close方法,必须先关闭IO流,才能刷过去 BufferedInputStream bis = new BufferedInputStream(new FileInputStream("致青春.avi")); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy12.avi" )); int b ; while((b = bis.read())!= -1) { bos.write(b); } bis.close(); bos.close();
|