输入流与输出流复制粘贴内容

输入流与输出流复制粘贴内容

一、复制粘贴 (使用字节流)可复制任何文件包括图片、文档等

public static void main(String[] args) {
		FileInputStream fis=null;
		FileOutputStream fos=null;
		try {
			//字节输入流
			fis=new FileInputStream("C:/Users/Administrator/Desktop/test/bbb.txt");
			//字节输出流(创建流对象时写入路径可以判断文件是否存在如没有新建一个文件)
			fos=new FileOutputStream("C:/Users/Administrator/Desktop/test/ccc.txt");
			byte b[]=new byte[1024];
			int a=0;
			while (true) {
				a=fis.read(b);//每次循环读取1024字节
				if (a==-1) {//读取不到就跳出循环。
					break;
				}
				fos.write(b,0,a);//写入数据到文件(每次读取多少就写入多少)
			}
			fos.flush();//刷新
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				if (fis!=null) {
					fis.close();//关闭输入流
				}
				if (fos!=null) {
					fos.close();//关闭输出流
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

二、复制粘贴 (使用字符流)只能复制粘贴纯文本文件

public static void main(String[] args) {
		FileReader fr=null;
		FileWriter fw=null;
		try {
			fr=new FileReader("C:/Users/Administrator/Desktop/test/bbb.txt");
			fw=new FileWriter("C:/Users/Administrator/Desktop/test/fff.txt");
			char c[]=new char[20];
			int a=0;
			while (true) {
				a=fr.read(c);
				if (a==-1) {
					break;
				}
				fw.write(c,0,a);
			}
			fw.flush();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				if (fr!=null) {
					fr.close();
				}
				if (fw!=null) {
					fw.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

备注:
使用字符流只能复制粘贴纯文本文件(例如 .txt)。不能复制粘贴图片、音频、视频、word等文件。因为字符流就是字节流+编码表,而用字符流去复制图片时,字符流会默认将图片的字节码格式进行编码, 所以会导致复制后的图片与原图片可能不一致甚至会丢失数据。
所有我们在项目开发中读写文件尽量使用字节流。
文件都由字节组成

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值