FileIO Tools

     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();
	}

  

Guess you like

Origin www.cnblogs.com/yan-zm/p/12629439.html