读取本地文件 并解析


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class bb {
    public static void main1(String[] args) throws IOException {
        File file = ResourceUtils.getFile("classpath:dx.json");
        String json = FileUtils.readFileToString(file, "UTF-8");
        JSONObject jsonObject = JSON.parseObject(json);
        JSONArray features = jsonObject.getJSONArray("features");
        for (Object feature : features) {
            System.err.println(feature);
        }

    }

    public static void main(String[] args) {
        //1.读取JSON文件
        String jsonStr = null;
        try {
            ClassPathResource inputStream = new ClassPathResource("dx.json");
            InputStreamReader reader = new InputStreamReader(inputStream.getInputStream(), StandardCharsets.UTF_8);
            int ch = 0;
            StringBuilder sb = new StringBuilder();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            reader.close();
            jsonStr = sb.toString();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        JSONArray features = jsonObject.getJSONArray("features");
        for (Object feature : features) {
            JSONObject fea = JSONObject.parseObject(feature.toString());
            JSONObject properties = fea.getJSONObject("properties");
            String type = properties.getString("type");
            if ("1".equals(type)) {
                String name = properties.getString("Name");
                String layer = properties.getString("Layer");

                JSONObject geometry = fea.getJSONObject("geometry");
                //POINT(104.624 37.2831)
                String coordinates = geometry.getString("coordinates").replaceAll("\\[","").replaceAll("]","");
                String[] split = coordinates.split(",");
                System.err.println(name + "  " + "POINT(" + split[0] + " " + split[1] + ")");
            }

        }

    }
}


posted @ 2023-06-02 10:56  qwer78  阅读(34)  评论(0)    收藏  举报