码迷,mamicode.com
首页 > 其他好文 > 详细

FileIO工具类

时间:2020-04-03 23:46:45      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:content   cat   blank   ror   flush   public   put   exist   ring   

     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工具类

标签:content   cat   blank   ror   flush   public   put   exist   ring   

原文地址:https://www.cnblogs.com/yan-zm/p/12629439.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!