Java如何实现文件拷贝操作和如何正确关闭资源

来源:互联网 发布:用友通软件 编辑:程序博客网 时间:2024/05/22 11:53

使用字节流完成文件的拷贝:

使用字节输入流(FileInputStream)将源文件中的数据读进来,同时使用字节输出流(FileOutputStream)将读进来的数据写到目标文件中,即一边读一边写,完成文件的拷贝。

//使用字节流完成文件的拷贝操作public class FileStremCopyDemo {public static void main(String[] args) throws IOException {//创建目标与源对象File srcFile = new File("file/src.txt");//源对象File desFile = new File("file/des.txt");//目标文件//创建输入输出流InputStream in = new FileInputStream(srcFile);OutputStream out = new FileOutputStream(desFile);//IO 操作byte[] buffer = new byte[1024];//创建容量为1024的缓冲区(存储已经读取的字节数据)int len = -1;//表示已经读取了多少个字节数据,若果等于-1,表示已经读到最后while((len = in.read(buffer)) != -1){//数据在buffer数组中out.write(buffer, 0, len);}//关闭资源in.close();out.close();}}

上面程序实现文件的拷贝中,是直接将异常抛出去,一般这种情况是要处理异常的,按正常的try catch处理异常,我们会发现关闭资源的代码会很繁琐,如下:

//繁琐的资源关闭方式private static void test1() {File srcFile = new File("file/src.txt");File desFile = new File("file/des.txt");InputStream in = null;OutputStream  out = null;try {in = new FileInputStream(srcFile);out = new FileOutputStream(desFile);byte[] buffer = new byte[1024];int len = -1;while ((len = in.read(buffer)) != -1) {out.write(buffer);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (in != null) {in.close();}} catch (IOException e) {e.printStackTrace();}if (out != null) {try {out.close();} catch (IOException e) {e.printStackTrace();}}}}


从Java7开始,Java新添了一个特性,在try后面加上一个圆括号,将需要关闭的资源放到里面定义,程序执行完毕会自动帮我们关闭圆括号里面的资源,如下:

//Java7自动关闭资源private static void test2() {File srcFile = new File("file/src.txt");File desFile = new File("file/des.txt");try (InputStream in = new FileInputStream(srcFile);OutputStream out = new FileOutputStream(desFile);) {byte[] buffer = new byte[1024];int len = -1;while ((len = in.read(buffer)) != -1) {out.write(buffer);}}catch (IOException e) {e.printStackTrace();}}



0 0
原创粉丝点击