package com.zeekling.solo.wechat.util; import org.apache.commons.lang3.text.StrBuilder; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; /** * @author zeekling [lingzhaohui@zeekling.cn] * @version 1.0 * @apiNote 主要用来操作文件相关 * @since 2020-03-21 */ public final class FileUtils { private static final Logger LOG = LoggerFactory.getLogger(FileUtils.class); private FileUtils() { } /** * 读取文件 * * @param filePath 文件地址 * @return 文件内容 */ @SuppressWarnings("resource") public static String readFile(String filePath) { StrBuilder sb = new StrBuilder(); byte[] buffer = new byte[1024]; try { FileInputStream inputStream = new FileInputStream(filePath); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); int idx = -1; while ((idx = bufferedInputStream.read(buffer)) != -1) { sb.append(new String(buffer, 0, idx)); } } catch (IOException e) { LOG.warn("file read error,fileName:{}, error:{}", filePath, e); } return sb.toString(); } /** * 读取文件,并且将文件转换成json对象 * * @param filePath 文件路径 * @return 转换后的json对象 */ public static JSONObject readJsonFile(String filePath) { String str = readFile(filePath); try { return new JSONObject(str); } catch (Exception e) { LOG.warn("str to json error,str:{}, error:{}", str, e); } return new JSONObject(); } }