IO流的读和写(转换成Base64字符输出)

读:  InputStream in =null;
      String imageInformation="";
      List listPicture=imagedealDao.getPicture(picture,imageTypeArray);
     
      //对查询出的数据通过Path循环进行读取
      for (Picture pic : listPicture) {
       byte[] data=null;
       try {
       in =new FileInputStream(pic.getPath()); //取文件的路径
    try {
     data=new byte[in.available()];
     in.read(data);   //读到数组里
    } catch (IOException e) {
     log.error("读取磁盘数据出错");
     throw new ProcessException(ErrorCode.E_0000.getCode(),ErrorCode.E_0000.getMessage());
    }           
   } catch (FileNotFoundException e) {
    log.error("没有找到文件"+e.getMessage());
    throw new ProcessException(ErrorCode.E_0000.getCode(),ErrorCode.E_0000.getMessage());
   }finally{
    try {
     in.close();
    } catch (IOException e) {
     log.error("关闭流失败");
    }
   }
       //转换成Base64格式
    imageInformation=pic.getSubclassSort().concat("-").concat(Base64.encodeBase64String(data)).concat(",");
   
      }
   return imageInformation.substring(0,imageInformation.lastIndexOf(","));


写: List paths=insertPicture(picture,filesFileName); //取出路径集
        try{
    for (int i = 0; i < files.size(); i++) {
    File item = files.get(i);  //取出有那些文件
    String absolutePath =paths.get(i); //取出有那些路径
    String dir = absolutePath.substring(0,
      absolutePath.lastIndexOf("/"));
    File filedir = new File(dir);
    //判断这个路径是否存在,没有进行创建
    if (!filedir.exists()) {
     filedir.mkdirs();
     filedir.mkdir();
    }
    // 输出流
    OutputStream os = new FileOutputStream(new File(absolutePath));
    // 输入流
    InputStream is = new FileInputStream(item);

    byte[] buf = new byte[1024];
    int length = 0;
    
    while (-1 != (length = is.read(buf))) {
     os.write(buf, 0, length);
    }
    is.close();
    os.close();
   }
  }catch (ProcessException e) {
   logger.error(UPLOAD_ERROR_MSG, e);
   throw e;
  } catch (Exception e) {
   logger.error(UPLOAD_ERROR_MSG, e);
   throw new ProcessException(ResponseCode.E_1002.getCode(),
     UPLOAD_ERROR_MSG, e);
  }
  return paths;

你可能感兴趣的:(IO流的读和写(转换成Base64字符输出))