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自动关闭资源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里如何正确计算检验和
- 如何实现深度拷贝?
- AIX上静默安装WAS8.5.5.x的记录及思考
- leetcode--34--二分查找范围
- Markdown编辑器语法-格式设置
- Integer Inquiry
- (一)、一步一步学GTK+之开篇
- Java如何实现文件拷贝操作和如何正确关闭资源
- 计数排序
- Struts2笔记(持续更新)
- [Memcached系列]专题一:快速入门
- js学习笔记(四)表单验证
- Struts2学习——0200struts.xml初步解释
- 不同IO流对文本文件拷贝速度大小的比较
- redis持久化
- deepin/ubuntu 双系统安装Drcom时可能出现的问题