IO文件拷贝

利用java的IO流实现文件的拷贝。思路:

以程序为中转站的作用,对接输入流和输出流。便实现了文件的拷贝。也就是对上一篇博客两种流的结合。

https://blog.csdn.net/qq_40301026/article/details/87869205

                                            

源文件存放在study02下,命名为:ta.jpg

   

package cn.liu.io2;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class CopyFile {
	public static void main(String[] args) {
		try {
			copyFile("ta.jpg","www.jpg");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public static void copyFile(String source,String aim) throws InterruptedException {
		//1.创建源(输入--->输出)
		File in = new File(source);
		File out = new File(aim);
		
		InputStream is = null;
		OutputStream os = null;
		try {
			//2.选择流(输入---->输出)
			is = new FileInputStream(in);
			os = new FileOutputStream(out);
			
			//3.操作(先从输入接受进来存程序,再从程序输出到指定位置)
			//3.1分段读取
			byte[] flush = new byte[1024*1];
			int len=-1;//记录缓冲池的长度
			while((len=is.read(flush))!=-1) {
				//3.2读进来后到后再给写出去
				os.write(flush,0,len);
			}
			os.flush();//每次再刷新一下缓冲池
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			//4.释放资源  分别关闭,先打后关
			try {
				while(os!=null) {
					os.close();
				}
				
				while(is!=null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

执行结果:

按F5进行刷新就可以看到:新建的文件(www.jpg)

                                                          

打开后看到成功:

                             

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值