对三维数据进行裁剪
List<Range> tyxRanges = new ArrayList<>();
tyxRanges.add(new Range(null,0,12));
tyxRanges.add(new Range(null,0,12));
tyxRanges.add(new Range(null,0,12));
Array varData = varObject.read(tyxRanges);
ncWrite.write(varVar, varData);
只显示了左下角的区域。
增加对时间变量的裁剪
public String varExport(@ModelAttribute FileSaveVars params ) throws IOException, InvalidRangeException, ParseException {
// 0° 设置时间
String timeStart = "2018-01-01 00:30:00";
String timeEnd = "2018-01-01 00:40:00";
// 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° 设置需要转存的变量
String varName = "QLML";
// 4° 设置时间变量
Variable timeObject = ncFile.findVariable("time");
String timeAt = timeObject.getUnitsString();
String regex = "\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}";
Pattern p = Pattern.compile(regex);
Matcher matcher = p.matcher(timeAt);
if (matcher.find()) {
timeAt = matcher.group(0);
}
// 4-1° 获取时间差
int timeDiff1 = DateHelp.dateDifference(timeAt,timeStart);
int timeDiff2 = DateHelp.dateDifference(timeAt,timeEnd);
// 4-2° 获取时间步长
Array timeArray = timeObject.read();
int timeStep = (int)(timeArray.getFloat(1) - timeArray.getFloat(0)) ;
int startIndex = timeDiff1/timeStep;
int endIndex = timeDiff2/timeStep;
// 5° 获取需要转存的变量对象
Variable varObject = ncFile.findVariable(varName);
// 6° 构造输出保存文件
NetcdfFileWriter ncWrite = NetcdfFileWriter.createNew(NetcdfFileWriter.Version.netcdf4, savePath);
// 6° 设置文件的一些参数
// 7°-1纬度
for(Dimension dimension : varObject.getDimensions()){
System.out.println(dimension.getShortName());
System.out.println(dimension.getLength());
ncWrite.addDimension(null, dimension.getShortName(), dimension.getLength());
}
// 7°-2变量
Variable varVar = ncWrite.addVariable(null, varObject.getShortName(), varObject.getDataType(), varObject.getDimensionsString());
System.out.println(varVar.getDimensions());
// 7°-3设置属性
List<Attribute> AttrList = varObject.getAttributes();
for (Attribute att : AttrList) {
varVar.addAttribute(att);
}
// 8°创建
ncWrite.create();
// 9°将数据写入
List<Range> tyxRanges = new ArrayList<>();
tyxRanges.add(new Range(null,startIndex,endIndex));
tyxRanges.add(new Range(null,0,120));
tyxRanges.add(new Range(null,0,120));
Array varData = varObject.read(tyxRanges);
ncWrite.write(varVar, varData);
// 10°关闭保存
ncWrite.close();
return "OK";
}