Java는 txt 파일을 읽고 구문 분석합니다.

利用org.json即可实现

1. 기본 아이디어

먼저 IO 스트림을 사용하여 txt 파일을 읽고 각 줄의 내용을 읽고 일반 문자열로 변환(json 형식의 형식이 정확해야 함)한 다음 JSONObject 개체로 변환하고 JSONObject 개체를 사용합니다. 다양한 유형의 값을 얻습니다.
txt 파일 내용 형식은 다음과 같습니다.
여기에 이미지 설명 삽입

두, 특정 코드

코드는 다음과 같습니다(예제).

public static void main(String[] args) throws IOException {
    
    
        String jsonpath="E:\\河南省乡镇点\\12.txt";
        ReadGeojson.ReadGeojsonFile(jsonpath);
    }
    public static void ReadGeojsonFile(String jsonpath) throws IOException {
    
    
        //读取txt文件流
        File file=new File(jsonpath);
        FileInputStream fileInputStream = new FileInputStream(file);
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"UTF-8");
        BufferedReader bufReader = new BufferedReader(inputStreamReader);
        try {
    
    
            String  line="";
            //读取每行内容
            StringBuffer sb=new StringBuffer();
            while ((line=bufReader.readLine())!=null){
    
    
                sb.append(line);
            }
            //去除空格
            String sbreplace = sb.toString().replace(" ", "");
            System.out.println(sbreplace);
            //转换成为JSONObject对象
            JSONObject jsonObj =new JSONObject(sbreplace);
            System.out.println(jsonObj.get("dataType"));
            //第二层
            Object attributes = jsonObj.get("attributes");
            System.out.println(attributes);
            JSONObject attributesObj =new JSONObject(attributes.toString());
            System.out.println(attributesObj.get("userId"));
            //数组形式
            JSONArray geometry =(JSONArray) jsonObj.get("geometry");
            System.out.println(geometry.get(0));
            System.out.println(geometry.toString());

        } catch (IOException  e) {
    
    
            e.printStackTrace();
        }

        bufReader.close();
    }

결과는 다음과 같습니다

여기에 이미지 설명 삽입

요약하다

txt 파일의 형식이 json 형식의 요구 사항을 충족하지 않으면 JSONObject jsonObj =new JSONObject(sbreplace)에서 오류가 발생합니다. 이 단계는 일반적으로 JSONObject 텍스트가 1에서 '{'로 시작해야 합니다. ], 등.

추천

출처blog.csdn.net/qq_37967853/article/details/127494272