《黑马程序员》 IO之复制图片

class Demo9 
{
	/*
		复制图片
	      复制d盘的图片到e盘中
		   像多媒体文件及图片资源,操作它最好使用字节流
		    因为使用字符流可能会出现无法浏览的情况
	*/
	public static void main(String[] args) 
	{
		File src=new File("d:\\temp.png");
		//获取源文件绝对路径
		String srcPath=src.getAbsolutePath();
		//获取文件路径截取文件名然后组拼成新的文件路径
		String destPath="e:\\"+srcPath.substring(srcPath.lastIndexOf("\\")+1);
		File dest=new File(destPath);
		copyPic(src,dest);
	}

	public static void copyPic(File src,File dest){
		InputStream fis=null;  //要进行初始化
		OutputStream fos=null;  //要进行初始化
		try{
			fis=new FileInputStream(src);
			fos=new FileOutputStream(dest);
			//创建缓冲区
			byte[] buffer=new byte[1024];
			int len; //记录读取到的数据的个数
			while((len=fis.read(buffer))!=-1){
				//把读取到的数据写入到文件中
				//只写缓冲区中的有效位
				fos.write(buffer,0,len);
			}
			//关闭流:虽说可以不关,但是关上还是好一些
			fis.close();
			fos.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值