java裁切NC文件并转成Json

发布时间 2023-08-24 14:45:08作者: 方大帝的博客
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.junit.Test;
import ucar.ma2.Index;
import ucar.nc2.NetcdfFile;
import ucar.ma2.Array;

import java.io.FileWriter;
import java.io.IOException;

public class NetCDF2JSON {

    @Test
    public void test() {
        cut2Json("V-000.nc", 0, 70, 70, 150);
    }

    public void cut2Json(String ncPath, double minLat, double maxLat, double minLon, double maxLon) {
        try {
            // 打开 NetCDF 文件
            NetcdfFile inputFile = NetcdfFile.open(ncPath);

            // 获取经纬度变量
            Array latArray = inputFile.findVariable("lat").read();
            Array lonArray = inputFile.findVariable("lon").read();
            Array dataArray = inputFile.findVariable("V").read();

            // 获取经纬度索引范围
            int minLatIndex = findIndex(latArray, minLat);
            int maxLatIndex = findIndex(latArray, maxLat);
            int minLonIndex = findIndex(lonArray, minLon);
            int maxLonIndex = findIndex(lonArray, maxLon);

            // 计算 dx 和 dy
            double dx = (maxLat - minLat) / (minLatIndex - maxLatIndex);
            double dy = (maxLon - minLon) / (maxLonIndex - minLonIndex);

            // 创建 Index 对象
            Index index = dataArray.getIndex();
            JSONArray jsonArray = new JSONArray();
            for (int i = maxLatIndex; i <= minLatIndex; i++) {
                JSONArray rowArray = new JSONArray();
                for (int j = minLonIndex; j <= maxLonIndex; j++) {
                    rowArray.add(dataArray.getDouble(index.set(0, i, j)));
                }
                jsonArray.add(rowArray);
            }

            JSONObject jsonObject = new JSONObject(true);
            jsonObject.put("minLat", minLat);
            jsonObject.put("maxLat", maxLat);
            jsonObject.put("minLon", minLon);
            jsonObject.put("maxLon", maxLon);
            jsonObject.put("dx", dx);
            jsonObject.put("dy", dy);
            jsonObject.put("data", jsonArray);

            // 将 JSON 数组写入到文件
            try (FileWriter fileWriter = new FileWriter("aaa.json")) {
                fileWriter.write(jsonObject.toJSONString());
            } catch (IOException e) {
                e.printStackTrace();
            }

            // 关闭文件
            inputFile.close();

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


    // 查找最接近的索引
    public int findIndex(Array array, double target) {
        double[] values = (double[]) array.get1DJavaArray(double.class);
        int index = 0;
        double minDifference = Double.MAX_VALUE;

        for (int i = 0; i < values.length; i++) {
            double difference = Math.abs(values[i] - target);
            if (difference < minDifference) {
                minDifference = difference;
                index = i;
            }
        }
        return index;
    }
}