javaIO流中文件的拷贝和图片的拷贝

 文件拷贝实例:

利用文件输入输出流编写一个实现文件拷贝的程序, 源文件名和目标文件名通过控制台输入。

public class Copy {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.print("请输入您要拷贝的源文件:");
		String str = sc.next();
		System.out.print("请输入您要拷贝的目标文件:");
		String s = sc.next();
		/*
		 * 方法一:
		 * try {
			FileInputStream fis = new FileInputStream(str);
			byte[] b=new byte[fis.available()];
			fis.read(b);
			System.out.println("源文件内容:");
			System.out.println(new String(b));
			fis.close();						
			try {
				FileOutputStream fos = new FileOutputStream(s);
				String st = new String(b);
				fos.write(st.getBytes());
				fos.flush();
				fos.close();
				System.out.println("文件拷贝成功!");
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();				
			}	
		} catch (FileNotFoundException e) {
			System.out.println("源文件未找到!");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/		
		//方法二:
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream(str);
			fos = new FileOutputStream(s);
			byte[] b = new byte[fis.available()];
			while (fis.read(b)!=-1) {		        
			        fos.write(b);	        
			    }			
			System.out.println("文件拷贝成功!");
		} catch (FileNotFoundException e) {
			System.out.println("源文件未找到!");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				if(fis != null){
					fis.close();					
				}
				if(fos != null){
					fos.flush();
					fos.close();
				}	
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}		
	}
}
图片拷贝实例:

将图片根据原路径拷贝到另一个路径内

public class PictureCopy {

	public static void main(String[] args) {

		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream("E:/iodemo/99.jpg");
			fos = new FileOutputStream("E:/iodemo/00.jpg");	
			byte [] b = new byte[fis.available()];	    
		    while (fis.read(b)!=-1) {		        
		        fos.write(b);	        
		    }
			fos.close();
			System.out.println("图片拷贝成功!");
		} catch (FileNotFoundException e) {
			System.out.println("源文件未找到!");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			//finally关键字:无论出不出现异常最后都要执行finally语句中的代码
			//最后再关闭流
			try {
				if(fis!=null){
					fis.close();
				}			
				if(fos != null){
					fos.flush();
					fos.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}		
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值