IO流的基础案例

5 篇文章 0 订阅
3 篇文章 0 订阅

文件复制

public class Test4_Copy {
       public static void main(String[] args) throws Exception {
            // 1,创建读取文件和写出文件
            File from = new File("D:\\teach\\a\\1.txt");
            File to = new File("D:\\teach\\a\\to.txt");
				
			//调用copy完成文件复制
			copy(from, to);
       } 
       
       //封装了文件复制的工具,将来可以通过类名.直接调用
       public static void copy(File from, File to) throws Exception {
	       // 2,读取from,写出到to
           InputStream in = new FileInputStream(from);
           OutputStream out = new FileOutputStream(to); 
           // 3,开始读,读到-1为止
           int b = 0;// 记录每次读取到的数据
		   while ((b = in.read()) != -1) {
             	out.write(b);// 把读到的内容写出去
            } 
              // 4,关闭资源
              in.close();
              out.close();
       }
}

批量读写

public class Test4_Copy {
       public static void main(String[] args) throws Exception {
              // 1,创建读取文件和写出文件
              File from = new File("D:\\teach\\a\\1.txt");
              File to = new File("D:\\teach\\a\\to.txt");
              
              copyByte(from, to);// 一个字节一个自己的复制
              copyArray(from, to);// 一个数组一个数组的复制 
       } 
       
       // 一个数组一个数组的复制
       private static void copyArray(File from, File to) throws Exception {
              // 2,读取from,写出到to
              InputStream in = new FileInputStream(from);
              OutputStream out = new FileOutputStream(to); 
              // 3,批量的读和写
              int b = 0;// 记录每次读取到的数据
              //源码:数组默认的长度一般是8M数组的长度就是8*1024
              byte[] bs = new byte[8*1024];//用来缓存数据
              while ((b = in.read(bs)) != -1) {//读取数组中的内容
                     out.write(bs);// 把读到的数组里的内容写出去
              } 
              
              // 4,关闭资源
              in.close();
              out.close(); 
       } 
       
       // 封装了文件复制的工具,将来可以通过类名.直接调用
       public static void copyByte(File from, File to) throws Exception {
              // 2,读取from,写出到to
              InputStream in = new FileInputStream(from);
              OutputStream out = new FileOutputStream(to); 
              
              // 3,开始读,读到-1为止
              int b = 0;// 记录每次读取到的数据
              while ((b = in.read()) != -1) {
                     out.write(b);// 把读到的内容写出去
              } 
              
              // 4,关闭资源
              in.close();
              out.close();
       }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值