我的文件主要是json格式,需要其中的一些数据,在数据量较大时,直接进行以读取文件的方式把数据进行添加
文件内容示例:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
以下用了2种方式,第一种较为方便,根据自己需要选择
1将文件内容读取成个字符串
@Test
public void readFile1() throws IOException {
ObjectMapper mapper = new ObjectMapper();
File file = new File("D:\\b.txt");
//文件内容为json格式
String content = new String(java.nio.file.Files.readAllBytes(file.toPath()));
JsonNode node = mapper.readTree(content);
for (JsonNode item : node) {
String s = item.get("city").asText();
System.out.println("city:" + s);// 输出所有
}
}
结果
2将文件内容读取为集合
@Test
public void readFile2() throws IOException {
String path = "D:\\b.txt";
List<String> lines = Files.readLines(new File(path), StandardCharsets.UTF_8);
JSONArray array = JSONArray.parseArray(lines.toString());
for (Object obj : array) {
JSONArray innerArray = (JSONArray) obj;
for (Object innerObj : innerArray) {
//处理后获取里面需要的数据
JSONObject jsonObject = (JSONObject) innerObj;
String id = jsonObject.getString("id");
String city = jsonObject.getString("city");
System.out.println("id: " + id + ", city: " + city);
}
}
}