首先附上工具類代碼:
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.nio.charset.StandardCharsets;
/**
* @author chenzhen
* Created by chenzhen on 2020/5/6.
*/
@Slf4j
public class FileUtils {
public static JSONObject readJsonFile(String fileName) {
String jsonStr = "";
try {
RandomAccessFile rf = new RandomAccessFile(fileName,"rws");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = rf.read()) != -1) {
sb.append((char) ch);
}
rf.close();
jsonStr = sb.toString();
return JSONObject.parseObject(jsonStr);
} catch (Exception e) {
e.printStackTrace();
return new JSONObject();
}
}
public static JSONArray readJsonArrayFile(String hostListPath) {
String jsonStr = "";
try {
RandomAccessFile rf = new RandomAccessFile(hostListPath,"rws");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = rf.read()) != -1) {
sb.append((char) ch);
}
rf.close();
jsonStr = sb.toString();
return JSONArray.parseArray(jsonStr);
} catch (Exception e) {
e.printStackTrace();
return new JSONArray();
}
}
public static boolean writeJSONStringToFile(String toJSONString, String filePath) {
try {
File file = new File(filePath);
if (file.exists()){
boolean delete = file.delete();
if (delete){
log.info("文件已清理,準備創建");
}else {
log.info("文件被鎖,清理創建");
}
}
boolean newFile = file.createNewFile();
if (newFile){
log.info("新文件已創建,準備寫入");
}else {
log.info("新文件創建失敗");
}
RandomAccessFile rf = new RandomAccessFile(filePath,"rws");
rf.write(toJSONString.getBytes());
rf.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
考慮到在寫文件的時候會出現髒數據,所以就考慮使用RandomAccessFile類來做,使用rws模式,方便快捷完成鎖機制的處理。有啥問題大家評論見