IO流

字符流

使用字符流进行文本复制:

	public  void test1()  {
		//创建输入/输出流对象
		FileReader fr = null;
		FileWriter fw = null;
		try {
			//创建File类,指明读入/写出文件
			File srcFile = new File("hello.txt");
			File destFile = new File("hello2.txt");
			fr = new FileReader(srcFile);
			fw = new FileWriter(destFile);
			//进行读入写出操作
			char[] cbuf = new char[10];//每次读是个字符
			int len;//用于记录每次读入到数组中的个数
			while((len=fr.read(cbuf)) != -1){
				//每次写出len个字符
				fw.write(cbuf,0,len);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			//关闭流
		try {
			if(fr != null){
			fr.close();
			}
			if(fw != null){
			fw.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		}
	}

字节流

使用字节流进行非文本文件的复制:

public  void test1()  {
		//创建输入/输出流对象
		FileInputStream fis= null;
		FileOutputStream fos= null;
		try {
			//创建File类,指明读入/写出文件
			File srcFile = new File("01.jpg");
			File destFile = new File("02.jpg");
			fis= new FileInputStream(srcFile);
			fos= new FileOutputStream(destFile);
			//进行读入写出操作
			int count = 0; 
			  while (count == 0) { 
			   count = input.available(); 
			  }
			byte[] buffer = new byte[count];
			int len;//用于记录每次读入到数组中的个数
			while((len=fis.read(buffer)) != -1){
				//每次写出len个字符
				fos.write(buffer,0,len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			//关闭流
		try {
			if(fis!= null){
			fis.close();
			}
			if(fos!= null){
			fos.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		}
	}

缓冲流

缓冲流比节点流处理文件速度更快

使用缓冲流进行非文本文件的复制:

public  void test1()  {
		//创建输入/输出流对象
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			//创建File类,指明读入/写出文件
			File srcFile = new File("01.jpg");
			File destFile = new File("02.jpg");
			FileInputStream fis = new FileInputStream(srcFile);
			FileOutputStream fos = new FileOutputStream(destFile);
			//创造缓冲流
			bis = new BufferedInputStream(fis);
			bos = new BufferedOutputStream(fos);
			//进行读入写出操作
			byte[] buffer = new byte[10];//每次读是个字符
			int len;//用于记录每次读入到数组中的个数
			while((len=fis.read(buffer)) != -1){
				//每次写出len个字符
				fos.write(buffer,0,len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			//关闭流
		try {
			if(bis != null){
				bis.close();
			}
			if(bos != null){
				bos.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		}
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值