1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > Java io流文件读取和写入

Java io流文件读取和写入

时间:2019-05-24 21:24:40

相关推荐

Java io流文件读取和写入

Java io 流操作demo类

1.读取操作

/***@author lxw*@date /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 /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 /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();}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。