blog-weixin/src/main/java/com/zeekling/solo/wechat/util/FileUtils.java

65 lines
1.7 KiB
Java
Raw Normal View History

2020-03-21 04:21:52 +00:00
package com.zeekling.solo.wechat.util;
2020-03-21 04:54:29 +00:00
import org.apache.commons.lang3.text.StrBuilder;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
2020-03-21 04:21:52 +00:00
/**
* @author zeekling [lingzhaohui@zeekling.cn]
* @version 1.0
2020-03-21 04:54:29 +00:00
* @apiNote 主要用来操作文件相关
2020-03-21 04:21:52 +00:00
* @since 2020-03-21
*/
2020-03-21 04:54:29 +00:00
public final class FileUtils {
private static final Logger LOG = LoggerFactory.getLogger(FileUtils.class);
private FileUtils() {
}
/**
* 读取文件
*
* @param filePath 文件地址
* @return 文件内容
*/
2020-10-08 13:06:48 +00:00
@SuppressWarnings("resource")
public static String readFile(String filePath) {
2020-03-21 04:54:29 +00:00
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对象
*/
2020-03-21 10:29:30 +00:00
public static JSONObject readJsonFile(String filePath) {
2020-03-21 04:54:29 +00:00
String str = readFile(filePath);
try {
return new JSONObject(str);
} catch (Exception e) {
LOG.warn("str to json error,str:{}, error:{}", str, e);
}
2020-03-21 10:29:30 +00:00
return new JSONObject();
2020-03-21 04:54:29 +00:00
}
2020-03-21 04:21:52 +00:00
}