java IO流的学习1

IO流按流向分为:输出流和输入流。

按操作数据分为:字节流和字符流。

对于IO流的学习本人是从以下几个例子入手的。

例1.复制文本D:test.txt到E盘下

public class CopyText {

 /**
  * @param args
  */
 public static void main(String[] args) {
  BufferedReader bufr = null;
  BufferedWriter bufw = null;
  try {
   bufr = new BufferedReader(new FileReader("D:\\test.txt"));//读取源文件 如果不存在会报错
   bufw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("E:\\test_copy.txt"),"utf-8"));
   //目标文件路径  OutputStreamWriter可设置写入文件的编码如"utf-8"要与源文件一致才可读出正确数据
   String len = null;
   while((len=bufr.readLine())!=null){//缓存类提供了逐行读取
    bufw.write(len);
    bufw.newLine();//换行
   }
  } catch (FileNotFoundException e) {
   throw new RuntimeException("文件不存在");
  } catch (IOException e) {
   throw new RuntimeException("复制文件失败");
  }finally{
   if(bufr!=null)
    try {
     bufr.close();
    } catch (IOException e) {
     throw new RuntimeException("读关闭失败");
    }
   if(bufw!=null)
    try {
     bufw.close();
    } catch (IOException e) {
     throw new RuntimeException("写关闭失败");
    }
  }
 }

}


例2.复制图片D:\\1.bmp到E盘目录下

 private static void copy1() {
  BufferedInputStream ips = null;
  BufferedOutputStream ops = null;
  try {
   ips = new BufferedInputStream(new FileInputStream("D:\\1.bmp"));
   ops = new BufferedOutputStream(new FileOutputStream("E:\\1_copy.bmp"));
   int i = 0;
   while((i=ips.read())!=-1){
    ops.write(i);
   }
  } catch (FileNotFoundException e) {
   throw new RuntimeException("文件不存在");
  } catch (IOException e) {
   throw new RuntimeException("读写文件失败");
  }finally{
   if(ips!=null)
    try {
     ips.close();
    } catch (IOException e) {
     throw new RuntimeException("读关闭失败");
    }
   if(ops!=null)
    try {
     ops.close();
    } catch (IOException e) {
     throw new RuntimeException("写文件失败");
    }
  }
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值