Java基础复习:文件拷贝

来源:互联网 发布:美食软件 知乎 编辑:程序博客网 时间:2024/06/10 17:17

(1)利用字节输入输出流完成文件拷贝

package day20.filecopy;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;public class Demo1 {public static void main(String[] args) {File srcF = new File("d:/Test/笔记.txt");File destF = new File("d:/Test/hi.txt");fileCopy(srcF,destF);//无论是文本还是图片,都能拷贝成功}public static void fileCopy(File srcFile,File destFile){//文件非空检查if(srcFile == null || destFile == null){System.out.println("The file is null");return ;}InputStream is = null;OutputStream os = null;try {is = new FileInputStream(srcFile);os = new FileOutputStream(destFile);//len表示已经读取的字节数,若len!=-1表示文件读完了int len = 0;//buff缓冲区byte[] buff = new byte[1024];while((len=is.read(buff))!=-1){os.write(buff, 0, len);}System.out.println("您的文件拷贝成功!");} catch (IOException e) {e.printStackTrace();} finally {try {os.close();//先关os} catch (IOException e) {e.printStackTrace();} finally {try {is.close();//无论os是否关闭都应该关闭is} catch (IOException e) {e.printStackTrace();}}}}}

这种方式下的拷贝操作最复杂的地方在异常处理,尤其是在关闭资源时,异常处理更为累赘。

从java 7开始,新增了“资源自动关闭”的特性,称为 try-with-resource

 

(2)利用自动关闭资源新特性完成文件拷贝操作

import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;public class Demo2 {public static void main(String[] args) {File srcF = new File("d:/Test/笔记.txt");File destF = new File("d:/Test/hi.txt");fileCopy(srcF,destF);//无论是文本还是图片,都能拷贝成功}public static void fileCopy(File srcFile,File destFile){//文件非空检查if(srcFile == null || destFile == null){System.out.println("The file is null");return ;}try(InputStream is = new FileInputStream(srcFile);OutputStream os = new FileOutputStream(destFile);) {//len表示已经读取的字节数,若len!=-1表示文件读完了int len = 0;//buff缓冲区byte[] buff = new byte[1024];while((len=is.read(buff))!=-1){os.write(buff, 0, len);}System.out.println("您的文件拷贝成功!");} catch (IOException e) {e.printStackTrace();} }}


如上,通过这种方式,大大的减少了异常处理的代码,也使得程序的结构更为清晰明了。

其格式如下:

try(//在这里声明变量,打开资源//要求对象必须实现java.lang.AutoCloseable接口){//这里进行IO操作}catch(IOException e){e.printStackTrace();}


 

原创粉丝点击