FileIO工具类
Posted yan-zm
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了FileIO工具类相关的知识,希望对你有一定的参考价值。
private static final String DEFAULT_PATH = "D:\default_path"; private static final String DEFAULT_NAME = "default_name.txt"; public static void write2Disk(String path, String fileName,String content) { if (StringUtils.isBlank(content)) { return; } if (StringUtils.isBlank(path)) { path = DEFAULT_PATH; } if (StringUtils.isBlank(fileName)) { fileName = DEFAULT_NAME; } if (!new File(path).exists()) { new File(path).mkdir(); } BufferedOutputStream fos = null; try { fos = new BufferedOutputStream(new FileOutputStream(path + File.separator + fileName)); fos.write(content.getBytes(), 0, content.getBytes().length); fos.flush(); log.info("写出文件到 {} 成功",path + File.separator + fileName); } catch (IOException e) { log.error("FileOutputStream IOException:", e); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { log.error("FileOutputStream Close Error"); } } } } public static String read(String path, String fileName) { if (StringUtils.isBlank(path)) { path = DEFAULT_PATH; } if (StringUtils.isBlank(fileName)) { fileName = DEFAULT_NAME; } BufferedInputStream bis = null; StringBuilder sb = null; try { bis = new BufferedInputStream(new FileInputStream(path + File.separator + fileName)); byte[] buffer = new byte[1024]; sb = new StringBuilder(); int length = 0; if ((length = bis.read(buffer)) != -1) { sb.append(new String(buffer, 0, length)); } } catch (IOException e) { log.error("BufferedInputStream IOException:", e); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { log.error("BufferedInputStream Close Error"); } } } return sb == null ? StringUtils.EMPTY : sb.toString(); }
以上是关于FileIO工具类的主要内容,如果未能解决你的问题,请参考以下文章