copy 从输入流到输出流

/**
 * @author dawson dong
 */

package com.kisstools.utils;

import java.io.InputStream;
import java.io.OutputStream;

public class IoUtil {

   // 4k buffer
   public static final int BUFFER_SIZE = 4096;

   public static boolean copy(InputStream is, OutputStream os) {
      final byte[] buffer = new byte[BUFFER_SIZE];
      try {
         int count;
         while ((count = is.read(buffer)) != -1) {
            os.write(buffer, 0, count);
         }
         os.flush();
      } catch (Exception e) {
         return false;
      }
      return true;
   }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中的输入输出是用来处理数据的重要概念。输入用于读取数据,输出用于将数据写入目标位置。下面是有关Java输入输出的知识点和示例代码: 1. Java输入 Java中的输入用于从文件、网络连接、标准输入等位置读取数据。常用的输入有FileInputStream、BufferedInputStream和DataInputStream等。下面是一个基本的读取文件内容的示例代码: ``` try (FileInputStream fis = new FileInputStream("example.txt")) { int b; while ((b = fis.read()) != -1) { System.out.print((char) b); } } catch (IOException e) { e.printStackTrace(); } ``` 2. Java输出 Java的输出用于将数据写入到文件、网络连接、标准输出等位置。常用的输出有FileOutputStream、BufferedOutputStream和DataOutputStream等。下面是一个将数据写入文件的示例代码: ``` try (FileOutputStream fos = new FileOutputStream("example.txt")) { String str = "Hello, World!"; byte[] bytes = str.getBytes(); fos.write(bytes); } catch (IOException e) { e.printStackTrace(); } ``` 3. Java缓冲输入输出 Java提供了缓冲输入输出来提高读写效率。缓冲输入输出可以在读写数据时缓存一定量的数据,以减少对底层输入输出的访问次数。常用的缓冲输入输出有BufferedInputStream和BufferedOutputStream等。下面是一个使用缓冲输入输出读写文件的示例代码: ``` try (FileInputStream fis = new FileInputStream("example.txt"); BufferedInputStream bis = new BufferedInputStream(fis); FileOutputStream fos = new FileOutputStream("example_copy.txt"); BufferedOutputStream bos = new BufferedOutputStream(fos)) { byte[] bytes = new byte[1024]; int len; while ((len = bis.read(bytes)) != -1) { bos.write(bytes, 0, len); } } catch (IOException e) { e.printStackTrace(); } ``` 以上就是Java输入输出的基本知识点和示例代码。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值