调用方法
//读取json文件
String a = getDatafromFile();
JSONArray objects = JSONObject.parseArray(a);
// Object o = objects.get(0);
for(Object o:objects) {
message message = JSONObject.parseObject(o.toString(), message.class);
System.out.println();
}
//写文件
message m = new message();
m.setMixStationId("1");
m.setFlag("高级超标");
m.setMixStationName("fjfjfgyu拌合站");
List<message> dto =new ArrayList<>();
dto.add(m);
m.setMixStationId("2");
dto.add(m);
writeFileDto(dto);
读取文件
public static message readFileDto(){
File file = new File("/Users/yexin/Desktop/t.json");
if(!file.exists()){
return null;
}
message dto = null;
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while((line = br.readLine()) != null){
sb.append(line);
}
dto = JSONObject.parseObject(sb.toString(),message.class);
br.close();
} catch (UnsupportedEncodingException | FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return dto;
}
private String getDatafromFile(/*String fileName*/) {
String Path="/Users/yexin/Desktop/t.json";
BufferedReader reader = null;
String laststr = "";
try {
FileInputStream fileInputStream = new FileInputStream(Path);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
reader = new BufferedReader(inputStreamReader);
String tempString = null;
while ((tempString = reader.readLine()) != null) {
laststr += tempString;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return laststr;
}
写文件
/**
* 将对象写入缓存文件中
* @author
*/
public static void writeFileDto(List<message> dto){
File file = new File("/Users/yexin/Desktop/t.json");
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
String jsonStr = JSON.toJSONString(dto);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),"UTF-8"));
bw.write(jsonStr);
bw.flush();
bw.close();
} catch (UnsupportedEncodingException | FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
private void saveDataToFile(String fileName,String data) {
BufferedWriter writer = null;
File file = new File("d:\\"+ fileName + ".json");
//如果文件不存在,则新建一个
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
//写入
try {
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,false), "UTF-8"));
writer.write(data);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(writer != null){
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("文件写入成功!");
}
网友评论