Java如何实现文件拷贝操作和如何正确关闭资源
来源:互联网 发布:法兰克福和慕尼黑 知乎 编辑:程序博客网 时间:2024/06/04 18:40
http://blog.csdn.net/caidie_huang/article/details/52738225
使用字节流完成文件的拷贝:
使用字节输入流(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
- Java如何实现文件拷贝操作和如何正确关闭资源
- Java如何实现文件拷贝操作和如何正确关闭资源
- java多线程开发 如何正确关闭线程
- 如何实现文件的拷贝
- 如何正确关闭linux
- 如何正确关闭MongoDB
- 如何正确关闭MongoDB
- 如何正确关闭树莓派
- 如何正确关闭MongoDB
- 通过文件的拷贝例子,来详解文件资源的正确关闭的两种方法
- Java如何正确的使用try catch finally关闭文件流的总结
- 如何正确的打开和关闭相关Object,如 SPSite, SPWeb 等,从而避免内存资源的浪费?
- 如何正确关闭游戏服务器
- Java 如何实现InputStream的任意拷贝
- 如何批量拷贝文件
- 如何关闭v刹6.0中的资源文件
- java里如何正确计算检验和
- 如何实现深度拷贝?
- 使用Fragment+ViewPager使用过程中禁止预加载未展示Fragment页面的网络请求
- javascript 4-5章1
- mysql开放远程访问,授权用户数据库权限
- tomcat
- 由Monkey引发的测试工具方面的想法
- Java如何实现文件拷贝操作和如何正确关闭资源
- Lake Counting POJ
- VSCode开发C#(调用 Net Core)精简步骤说明
- webview记录滚动位置,下次打开滚动到记录点
- Android登录判断,并且在登录后跳转到相应的Activity
- Netty实现服务端客户端长连接通讯、心跳检测及自定义报文发送(一)
- u-boot命令-cmd编译过程
- laravel中Validator使用中出现的问题
- url 字符串截取