You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
61 lines
2.2 KiB
Java
61 lines
2.2 KiB
Java
1 year ago
|
import ucar.ma2.Array;
|
||
|
import ucar.ma2.Index;
|
||
|
import ucar.ma2.InvalidRangeException;
|
||
|
import ucar.nc2.NetcdfFile;
|
||
|
import ucar.nc2.NetcdfFiles;
|
||
|
import ucar.nc2.Variable;
|
||
|
|
||
|
import java.io.IOException;
|
||
|
import java.time.LocalDateTime;
|
||
|
import java.time.format.DateTimeFormatter;
|
||
|
|
||
|
/**
|
||
|
* Unit test for simple App.
|
||
|
*/
|
||
|
public class TestReadGrib2ByNC {
|
||
|
public static void main(String[] args){
|
||
|
// String ncFile = "surface.nc";
|
||
|
String file = "C:\\Users\\shi_y\\Desktop\\java_learn\\data_download\\GFSData\\UTC-20230910\\BJT-20230911-0200.grib2";
|
||
|
try (NetcdfFile ncFile = NetcdfFiles.open(file)) {
|
||
|
// 打印文件相关信息
|
||
|
// System.out.println(ncfile.toString());
|
||
|
|
||
|
// 获取时间变量
|
||
|
Variable timeVar = ncFile.findVariable("time");
|
||
|
String units = timeVar.findAttribute("units").getStringValue();
|
||
|
System.out.println(units);
|
||
|
// 读取时间变量 surface.nc的单位是"hours since 1900-01-01 00:00:00.0"
|
||
|
System.out.println(timeVar.getFileTypeId());
|
||
|
double[] timeArray = (double[]) timeVar.read().copyTo1DJavaArray();
|
||
|
|
||
|
DateTimeFormatter unitsFormat = DateTimeFormatter.ofPattern("'Hour since 'yyyy-MM-dd'T'HH:mm:ss'Z'");
|
||
|
LocalDateTime unitsDateTime = LocalDateTime.parse(units, unitsFormat).plusHours((long) timeArray[0]);
|
||
|
System.out.println(unitsDateTime);
|
||
|
// 指定变量名读取变量
|
||
|
Variable t2m = ncFile.findVariable("Temperature_isobaric");
|
||
|
|
||
|
// 打印变量的相关信息
|
||
|
System.out.println(t2m.toString());
|
||
|
|
||
|
if (t2m != null) {
|
||
|
System.out.println(t2m.findDimensionIndex("lon"));
|
||
|
}
|
||
|
// 读取所有的数据
|
||
|
assert t2m != null;
|
||
|
Array v = t2m.read("0, 0, 10:20, 20:30").reduce(0).reduce(0);
|
||
|
Index index = v.getIndex(); // 用于跟踪当前索引的位置
|
||
|
index = index.set(1);
|
||
|
System.out.println(v.getShort(index));
|
||
|
|
||
|
|
||
|
} catch (IOException ioe) {
|
||
|
// Handle less-cool exceptions here
|
||
|
throw new RuntimeException(ioe);
|
||
|
} catch (InvalidRangeException e) {
|
||
|
throw new RuntimeException(e);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
}
|
||
|
|