java中从文件读出byte[]后转String,再由String转为byte[],写文件

        项目需要,不使用IO流,只能通过服务器端传字符串发送给客户端,进行文件的下载操作。同时,文件的上传工作也通过传递字符串的方式进行的。

        感谢小白和冲~

        以下是具体代码。

/**
  * 根据文件获得文件的bytes的字符串格式
  * 
  * @param filePath
  * @return
  */
 public static String getFileBytes(String filePath) throws AppException {
  StringBuilder sb = null;
  byte[] btArray = null;
  FileInputStream fis = null;
  ByteArrayOutputStream bos = null;
  try {
   File file = new File(filePath);
   fis = new FileInputStream(file);
   bos = new ByteArrayOutputStream(1000);
   byte[] b = new byte[1000];
   int n;
   while ((n = fis.read(b)) != -1) {
    bos.write(b, 0, n);
   }
   btArray = bos.toByteArray();
   sb = new StringBuilder();
   for (int i = 0; i < btArray.length; i++) {
    byte bt = btArray[i];
    sb.append(bt);
    sb.append(',');
   }
   sb = sb.replace(sb.length() - 1, sb.length() - 1, "");
  } catch (FileNotFoundException e) {
   throw new AppException(CommonEnum.IOERROR.getKey(),
     CommonEnum.IOERROR.getValue());
  } catch (IOException e) {
   throw new AppException(CommonEnum.IOERROR.getKey(),
     CommonEnum.IOERROR.getValue());
  } finally {
   try {
    if (fis != null) {
     fis.close();
    }
    if (bos != null) {
     bos.close();
    }
   } catch (IOException e) {
    // TODO log
   }
  }
  return sb.toString();
 }

 /**
  * 根据刚刚生成的byte数组转换的String,生成文件
  */
 public static void creatFile(String fileContext, String fileName)
   throws AppException {
  BufferedOutputStream bos = null;
  FileOutputStream fos = null;
  File file = null;
  try {
   file = new File(fileName);
   File paraFile = file.getParentFile();
   if (!paraFile.exists()) {
    paraFile.mkdirs();
   }
   fos = new FileOutputStream(file);
   bos = new BufferedOutputStream(fos);
   String[] split = fileContext.toString().split(",");
   byte[] tt = new byte[split.length];
   for (int i = 0; i < split.length; i++) {
    tt[i] = new Byte(split[i]);
   }
   bos.write(tt);
  } catch (Exception e) {
   throw new AppException(CommonEnum.IOERROR.getKey(),
     CommonEnum.IOERROR.getValue());
  } finally {
   try {
    if (bos != null) {
     bos.close();
    }
    if (fos != null) {
     fos.close();
    }
   } catch (IOException e) {
    // TODO LOG
   }
  }
 }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值