java NIO方式读写文件

Java NIO(new/inputstream outputstream)使用通道、缓冲来操作流,所以要深刻理解这些概念,尤其是,缓冲中的数据结构(当前位置(position)、限制(limit)、容量(capacity))。

Channel(通道)、Buffer(缓冲区)、Selector(选择器)

/**
 * @author sy
 * @date 2020/2/13 19:31
 */
public class FileUtil implements Serializable {


  private static Logger log = LoggerFactory.getLogger(FileUtil.class);

  /**
   * 通过NIO获取byte[]
   * @param filename
   * @description 一般作用于从本地读取文件,通过httpServletResponse返回页面。
   * @return
   */
  public static byte[] toByteArray(String filename) {

    File f = new File(filename);
    if (!f.exists()) {
      log.error("文件未找到!" + filename);
      throw new RuntimeException("文件未找到");
    }
    FileChannel channel = null;
    FileInputStream fs = null;
    try {
      fs = new FileInputStream(f);
      channel = fs.getChannel();
      ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
      while ((channel.read(byteBuffer)) > 0) {
        // 读取中....
      }
      return byteBuffer.array();
    } catch (IOException e) {
      //实际上应该自定义异常,统一异常处理
      throw new RuntimeException("文件發生錯誤");
    } finally {
      try {
        channel.close();
      } catch (IOException e) {
        throw new RuntimeException("文件發生錯誤");
      }
      try {
        fs.close();
      } catch (IOException e) {
        throw new RuntimeException("文件發生錯誤");
      }
    }
  }


  /**
   * copy文件
   * @param src
   * @param dst
   * @description 一般作用于拷贝文件
   * @throws IOException
   */
  public static void copyFileUseNIO(String src,String dst) throws IOException{
    //声明源文件和目标文件
    FileInputStream fi = null;
    FileOutputStream fo = null;
    //获得传输通道channel
    FileChannel inChannel = null;
    FileChannel outChannel = null;
    try {
      //声明源文件和目标文件
      fi = new FileInputStream(new File(src));
      fo = new FileOutputStream(new File(dst));
      //获得传输通道channel
      inChannel = fi.getChannel();
      outChannel = fo.getChannel();
      //获得容器buffer
      ByteBuffer buffer = ByteBuffer.allocate(1024);
      while (true) {
        //判断是否读完文件
        int eof = inChannel.read(buffer);
        if (eof == -1) {
          break;
        }
        //重设一下buffer的position=0,limit=position
        buffer.flip();
        //开始写
        outChannel.write(buffer);
        //写完要重置buffer,重设position=0,limit=capacity
        buffer.clear();
      }
    }catch (Exception e){
      throw new RuntimeException("文件發生錯誤");
    }finally {
      try {
        inChannel.close();
        fi.close();
      } catch (IOException e) {
        throw new RuntimeException("文件發生錯誤");
      }
      try {
        outChannel.close();
        fo.close();
      } catch (IOException e) {
        throw new RuntimeException("文件發生錯誤");
      }
    }
  }

}

注:资料有从各大网站参考,如有雷同,纯属意外。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值