Java io流文件读取和写入

2 篇文章 0 订阅

Java io 流操作demo类

1.读取操作

 /**
     *@author lxw
     *@date 2020/6/24
     *@desc 获取文件输入流,这里读入内存中
     *@param [fileName]
     *@return byte[]
    **/
    public byte[] readPdfFile(String fileName) throws Exception{
        InputStream in = null;
        byte[] bytesRel;
        try {
            //读取Constants.PDF_CREATE_AND_SIGN.PDF_FILE_PATH路径下文件名位fileName的文件
            File f = new File(Constants.PDF_CREATE_AND_SIGN.PDF_FILE_PATH+fileName);
            in = new FileInputStream(f);
            //in.available 只适合于读取本地文件时判断流中字节数,不适合网络中的流数据大小判定
            bytesRel = new byte[ in.available()];
            in.read(bytesRel);
        } catch (IOException e) {
          log.error("读取文件{}失败!"+Constants.PDF_CREATE_AND_SIGN.PDF_FILE_PATH+fileName);
          throw new BizException(IfspRespCode.RESP_ERROR,"读取pdf文件失败!");
        }finally {
            if (in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    log.error("输入流关闭失败!原因:{}",e.getMessage());
                }
            }
        }
        return  bytesRel;
    }

2.写文件

 /**
     *@author lxw
     *@date 2020/6/24
     *@desc 写文件 如果想提高效率,可以使用缓冲流
     *@param [pdfByte, fileName]
     *@return void
    **/
    public void writePdfFile(byte[] pdfByte,String fileName) throws Exception{
        //检查文件是否已经存在,存在删除
        checkFIleExit(fileName,Constants.PDF_CREATE_AND_SIGN.PDF_FILE_PATH);
        OutputStream os = null;
        try {
            os = new FileOutputStream(Constants.PDF_CREATE_AND_SIGN.PDF_FILE_PATH+fileName);
            os.write( pdfByte ) ;
            os.flush() ;
        } catch (IOException e) {
            log.error("写入文件{}失败!"+Constants.PDF_CREATE_AND_SIGN.PDF_FILE_PATH+fileName);
        }finally {
            try {
                if (os!=null)  os.close();
            } catch (IOException e) {
                log.error("输入流关闭失败!原因:{}",e.getMessage());
            }
        }
    }


 /**
     *@author lxw
     *@date 2020/6/23
     *@desc 检查文件是否存在,存在就删除掉
     *@param [fileName, path]
     *@return void
    **/
    public void checkFIleExit(String fileName,String path){
        log.info("checkFIleExit方法入参:fileName:{},path:{}",fileName,path);
        File file = new File(path+fileName);
        if (file.exists()){
            file.delete();
        }
    }

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值