Netcdf中多变量导出代码示例

多个变量进行导出代码如下:

 @GetMapping("/export")
    public String varExport(@ModelAttribute FileSaveVars params ) throws IOException, InvalidRangeException {
//      1° 设置原始文件路径+转存文件路径
        String filePath = "/Users/caowei/workspace/jszone/大气系统/ncdemo/src/main/resources/static/MERRA2_400.tavg1_2d_flx_Nx.20180101.SUB.nc";
        String savePath = "/Users/caowei/workspace/test.nc";
//      2° 读取文件
        NetcdfFile ncFile = NetcdfFile.open(filePath, null);
 //     3° 构造输出保存文件
        NetcdfFileWriter ncWrite = NetcdfFileWriter.createNew(NetcdfFileWriter.Version.netcdf4, savePath);
//      4° 文件纬度
        for(Dimension dimension : ncFile.getDimensions()){
            ncWrite.addDimension(null, dimension.getName(), dimension.getLength());
        }
//      5° 设置需要转存的变量
        List<String> varNames = Arrays.asList("lon","lat","time","QLML");
        List<Variable> varArray = new ArrayList<>();
        for(String varName : varNames){
            Variable varObject = ncFile.findVariable(varName);
            Variable varVar = ncWrite.addVariable(null, varObject.getName().toString(), varObject.getDataType(),varObject.getDimensionsString());
            varVar.addAll(ncFile.findVariable(varName).getAttributes());
            varArray.add(varVar);
        }
//      6° 创建
        ncWrite.create();
//      7° 变量赋值
        for(Variable varItem:varArray){
            Array varData = ncFile.findVariable(varItem.getName()).read();
            ncWrite.write(varItem, varData);
        }
//      8°关闭保存
        ncWrite.close();
        return  "OK";
    }

你可能感兴趣的:(netcdf)