本文整理了Java中java.util.Formatter
类的一些代码示例,展示了Formatter
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Formatter
类的具体详情如下:
包路径:java.util.Formatter
类名称:Formatter
[英]Formats arguments according to a format string (like printf in C).
It's relatively rare to use a Formatter directly. A variety of classes offer convenience methods for accessing formatter functionality. Of these, String#format is generally the most useful. java.io.PrintStream and java.io.PrintWriter both offer format and printf methods.
Format strings consist of plain text interspersed with format specifiers, such as "name: %s weight: %03dkg\n". Being a Java string, the usual Java string literal backslash escapes are of course available.
Format specifiers (such as "%s" or "%03d" in the example) start with a % and describe how to format their corresponding argument. It includes an optional argument index, optional flags, an optional width, an optional precision, and a mandatory conversion type. In the example, "%s" has no flags, no width, and no precision, while "%03d" has the flag 0, the width 3, and no precision.
Not all combinations of argument index, flags, width, precision, and conversion type are valid.
Argument index. Normally, each format specifier consumes the next argument to format. For convenient localization, it's possible to reorder arguments so that they appear in a different order in the output than the order in which they were supplied. For example, "%4$s" formats the fourth argument ( 4$) as a string ( s). It's also possible to reuse an argument with Flags. The available flags are:
Flags,Use grouping separators for large numbers. (Decimal only.)format("%,d", 1024);1,234+Always show sign. (Decimal only.)format("%+d, %+4d", 5, 5);
+5, +5
A space indicates that non-negative numbers should have a leading space. (Decimal only.)format("x% d% 5d", 4, 4);
x 4 4
(Put parentheses around negative numbers. (Decimal only.)format("%(d, %(d, %(6d", 12, -12, -12);
12, (12), (12)
-Left-justify. (Requires width.)format("%-6dx", 5);
format("%-3C, %3C", 'd', 0x65);
5 x
D , E
0Pad the number with leading zeros. (Requires width.)format("%07d, %03d", 4, 5555);0000004, 5555#Alternate form. (Octal and hex only.) format("%o %#o", 010, 010);
format("%x %#x", 0x12, 0x12);10 010
12 0x12
Width. The width is a decimal integer specifying the minimum number of characters to be used to represent the argument. If the result would otherwise be shorter than the width, padding will be added (the exact details of which depend on the flags). Note that you can't use width to truncate a field, only to make it wider: see precision for control over the maximum width.
Precision. The precision is a . followed by a decimal integer, giving the minimum number of digits for d, o, x, or X; the minimum number of digits after the decimal point for a, A, e, E, f, or F; the maximum number of significant digits for g or G; or the maximum number of characters for s or S.
Conversion type. One or two characters describing how to interpret the argument. Most conversions are a single character, but date/time conversions all start with t and have a single extra character describing the desired output.
Many conversion types have a corresponding uppercase variant that converts its result to uppercase using the rules of the relevant locale (either the default or the locale set for this formatter).
This table shows the available single-character (non-date/time) conversion types:
String conversions
All types are acceptable arguments. Values of type Formattable have their formatTo method invoked; all other types use toString. sString.format("%s %s", "hello", "Hello");hello HelloSUppercase string.format("%S %S", "hello", "Hello");HELLO HELLOCharacter conversions
Byte, Character, Short, and Integer (and primitives that box to those types) are all acceptable as character arguments. Any other type is an error. cCharacter.format("%c %c", 'd', 'E');d ECUppercase character.format("%C %C", 'd', 'E');D EInteger conversions
Byte, Short, Integer, Long, and BigInteger (and primitives that box to those types) are all acceptable as integer arguments. Any other type is an error. dDecimal.format("%d", 26);26oOctal.format("%o", 032);32x, XHexadecimal.format("%x %X", 0x1a, 0x1a);1a 1AFloating-point conversions
Float, Double, and BigDecimal (and primitives that box to those types) are all acceptable as floating-point arguments. Any other type is an error. fDecimal floating point.
format("%f", 123.456f);
format("%.1f", 123.456f);
format("%1.5f", 123.456f);
format("%10f", 123.456f);
format("%6.0f", 123.456f);
123.456001
123.5
123.45600
123.456001
123
e, EEngineering/exponential floating point.
format("%e", 123.456f);
format("%.1e", 123.456f);
format("%1.5E", 123.456f);
format("%10E", 123.456f);
format("%6.0E", 123.456f);
1.234560e+02
1.2e+02
1.23456E+02
1.234560E+02
1E+02
g, GDecimal or engineering, depending on the magnitude of the value.format("%g %g", 0.123, 0.0000123);0.123000 1.23000e-05a, AHexadecimal floating point.format("%a", 123.456f);0x1.edd2f2p6Boolean conversion
Accepts Boolean values. null is considered false, and instances of all other types are considered true. b, BBoolean.format("%b %b", true, false);
format("%B %B", true, false);
format("%b", null);
format("%b", "hello");true false
TRUE FALSE
false
trueHash code conversion
Invokes hashCode on its argument, which may be of any type. h, HHexadecimal hash code.format("%h", this);
format("%H", this);
format("%h", null);190d11
190D11
nullZero-argument conversions%A literal % character.format("%d%%", 50);50%nNewline. (The value of System#lineSeparator.)format("first%nsecond");first\nsecond
It's also possible to format dates and times with Formatter, though you should use java.text.SimpleDateFormat (probably via the factory methods in java.text.DateFormat) instead. The facilities offered by Formatter are low-level and place the burden of localization on the developer. Using java.text.DateFormat#getDateInstance, java.text.DateFormat#getTimeInstance, and java.text.DateFormat#getDateTimeInstance is preferable for dates and times that will be presented to a human. Those methods will select the best format strings for the user's locale.
The best non-localized form is ISO 8601, which you can get with "%tF" (2010-01-22), "%tF %tR" (2010-01-22 13:39), "%tF %tT" (2010-01-22 13:39:15), or "%tF %tT%z" (2010-01-22 13:39:15-0800).
This table shows the date/time conversions, but you should use java.text.SimpleDateFormatinstead:
Date/time conversions
Calendar, Date, and Long (representing milliseconds past the epoch) are all acceptable as date/time arguments. Any other type is an error. The epoch is 1970-01-01 00:00:00 UTC. Use java.text.SimpleDateFormat instead. taLocalized weekday name (abbreviated).format("%ta", cal, cal);TuetALocalized weekday name (full).format("%tA", cal, cal);TuesdaytbLocalized month name (abbreviated).format("%tb", cal);AprtBLocalized month name (full).format("%tB", cal);ApriltcC library asctime(3)-like output. Do not use.format("%tc", cal);Tue Apr 01 16:19:17 CEST 2008tC2-digit century.format("%tC", cal);20td2-digit day of month (01-31).format("%td", cal);01tDAmbiguous US date format (MM/DD/YY). Do not use.format("%tD", cal);04/01/08teDay of month (1-31).format("%te", cal);1tFFull date in ISO 8601 format (YYYY-MM-DD).format("%tF", cal);2008-04-01thSynonym for %tb.tH2-digit 24-hour hour of day (00-23).format("%tH", cal);16tI2-digit 12-hour hour of day (01-12).format("%tI", cal);04tj3-digit day of year (001-366).format("%tj", cal);092tk24-hour hour of day (0-23).format("%tk", cal);16tl12-hour hour of day (1-12).format("%tl", cal);4tLMilliseconds.format("%tL", cal);359tm2-digit month of year (01-12).format("%tm", cal);04tM2-digit minute.format("%tM", cal);08tNNanoseconds.format("%tN", cal);359000000tpa.m. or p.m.format("%tp %Tp", cal, cal);pm PMtQMilliseconds since the epoch.format("%tQ", cal);1207059412656trFull 12-hour time ( %tI:%tM:%tS %Tp).format("%tr", cal);04:15:32 PMtRShort 24-hour time ( %tH:%tM).format("%tR", cal);16:15tsSeconds since the epoch.format("%ts", cal);1207059412tS2-digit seconds (00-60).format("%tS", cal);17tTFull 24-hour time ( %tH:%tM:%tS).format("%tT", cal);16:15:32ty2-digit year (00-99).format("%ty", cal);08tY4-digit year.format("%tY", cal);2008tzTime zone GMT offset.format("%tz", cal);+0100tZLocalized time zone abbreviation.format("%tZ", cal);CEST
As with the other conversions, date/time conversion has an uppercase format. Replacing %t with %T will uppercase the field according to the rules of the formatter's locale.
Number localization. Some conversions use localized decimal digits rather than the usual ASCII digits. So formatting 123 with %d will give 123 in English locales but ١٢٣ in appropriate Arabic locales, for example. This number localization occurs for the decimal integer conversion %d, the floating point conversions %e, %f, and %g, and all date/time %t or %T conversions, but no other conversions.
Thread safety. Formatter is not thread-safe.
[中]根据格式字符串格式化参数(如C中的printf)。
直接使用格式化程序相对较少。各种各样的类为访问格式化程序功能提供了方便的方法。其中,字符串格式通常是最有用的。JAVA木卫一。PrintStream和java。木卫一。PrintWriter都提供格式和printf方法。
格式字符串由插入格式说明符的纯文本组成,例如“名称:%s权重:%03dkg\n”。作为Java字符串,通常的Java字符串文本反斜杠转义当然是可用的。
格式说明符(例如示例中的“%s”或“%03d”)以%开头,并描述如何格式化其相应的参数。它包括可选参数索引、可选标志、可选宽度、可选精度和强制转换类型。在该示例中,“%s”没有标志、宽度和精度,而“%03d”有标志0、宽度3和精度。
并非参数索引、标志、宽度、精度和转换类型的所有组合都有效。
参数索引。通常,每个格式说明符使用下一个参数进行格式化。为了便于本地化,可以对参数进行重新排序,以便它们在输出中的显示顺序与提供它们的顺序不同。例如,“%4$s”将第四个参数(4$)格式化为字符串。还可以重用带有标志的参数。可用的标志有:
标记,对大数字使用分组分隔符。(仅限十进制。)格式(“%,d”,1024);1234+始终显示符号。(仅限十进制。)格式(“%+d,%+4d”,5,5)
+5, +5
空格表示非负数应有前导空格。(仅限十进制。)格式(“x%d%5d”,4,4)
x 4 4
(在负数周围加括号。(仅限十进制)格式(“%(d,%(d,%(6d),12,-12,-12)
12, (12), (12)
-左对齐。(需要宽度。)格式(“%-6dx”,5);
格式(“%-3C,%3C”,“d”,0x65)
5 x
D , E
0用前导零填充数字。(需要宽度。)格式(“%07d,%03d”,45555);00000045555#替代形式。(仅限八进制和十六进制。)格式(“%o%#o”,010,010);
格式(“%x%#x”,0x12,0x12);10 010
12 0x12
宽度宽度是一个十进制整数,指定用于表示参数的最小字符数。如果结果短于宽度,将添加填充(具体细节取决于标志)。请注意,不能使用“宽度”截断字段,而只能使其变宽:请参见“精度”以了解对最大宽度的控制。
精确精度是一个重要的指标。后跟一个十进制整数,表示d、o、x或x的最小位数;a、a、e、e、f或f小数点后的最小位数;g或g的最大有效位数;或s或s的最大字符数。
转换类型。描述如何解释论点的一两个字符。大多数转换都是单个字符,但是日期/时间转换都以t开头,并且有一个额外的字符来描述所需的输出。
许多转换类型都有相应的大写变量,该变量使用相关区域设置的规则(默认或为此格式化程序设置的区域设置)将其结果转换为大写。
此表显示了可用的单字符(非日期/时间)转换类型:
字符串转换
所有类型都是可接受的参数。Formattable类型的值调用了formatTo方法;所有其他类型都使用toString。串。格式(“%s%s”、“您好”、“您好”);你好,HelloSUppercase字符串。格式(“%S%S”、“您好”、“您好”);HELLO HELLOCharacter转换
Byte、Character、Short和Integer(以及对应于这些类型的原语)都可以作为字符参数。任何其他类型都是错误。C角色。格式(“%c%c”、“d”、“E”);d.大小写字符。格式(“%C%C”、“d”、“E”);D-EInteger转换
Byte、Short、Integer、Long和BigInteger(以及对应于这些类型的原语)都可以作为整数参数。任何其他类型都是错误。迪迈尔。格式(“%d”,26);26oOctal。格式(“%o”,032);32x,XHexadecimal。格式(“%x%x”,0x1a,0x1a);1a浮点转换
Float、Double和BigDecimal(以及与这些类型对应的原语)都可以作为浮点参数。任何其他类型都是错误。浮点
format("%f", 123.456f);
format("%.1f", 123.456f);
format("%1.5f", 123.456f);
format("%10f", 123.456f);
format("%6.0f", 123.456f);
<6$>>e,工程/指数浮点
format("%e", 123.456f);
format("%.1e", 123.456f);
format("%1.5E", 123.456f);
format("%10E", 123.456f);
format("%6.0E", 123.456f);
1.234560e+02
1.2e+02
1.23456E+02
1.234560E+02
1E+02
g、GDecimal或engineering,取决于值的大小。格式(“%g%g”,0.123,0.0000123);0.123000 1.23000e-05a,十六进制浮点。格式(“%a”,123.456f);0x1。EDD2F6Boolean转换
接受布尔值。null被视为false,所有其他类型的实例被视为true。b、 布卢恩。格式(“%b%b”,真,假);
格式(“%B%B”,真,假);
格式(“%b”,空);
格式(“%b”、“hello”);真假
真假
错误的
trueHash码转换
对其参数调用哈希代码,该参数可以是任何类型。h、 HHexadecimal哈希代码。格式(“%h”,此);
格式(“%H”,此);
格式(“%h”,空);190d11
190D11
nullZero参数转换%A文本%字符。格式(“%d%%”,50);50%的N线。(System#lineSeparator的值。)格式(“第一个%n秒”);第一个\n第二个
也可以使用Formatter格式化日期和时间,不过您应该使用java。文本SimpleDataFormat(可能通过java.text.DateFormat中的工厂方法)。Formatter提供的设施是低级的,将本地化的负担放在开发人员身上。使用java。文本DateFormat#getDateInstance,java。文本DateFormat#getTimeInstance和java。文本DateFormat#getDateTimeInstance更适合显示给用户的日期和时间。这些方法将为用户的区域设置选择最佳格式字符串。
最好的非本地化形式是ISO 8601,可以通过“%tF”(2010-01-22)、“%tF%tR”(2010-01-22 13:39)、“%tF%tT”(2010-01-22 13:39:15)或“%tF%tT%z”(2010-01-22 13:39:15-0800)获得。
此表显示了日期/时间转换,但您应该使用java。文本SimpleDataFormatInStead:
日期/时间转换
Calendar、Date和Long(表示超过历元的毫秒)都可以作为日期/时间参数。任何其他类型都是错误。纪元是1970-01-01 00:00:00 UTC。使用java。文本改为使用SimpleDataFormat。taLocalized工作日名称(缩写)。格式(“%ta”、校准、校准);星期二本地化工作日名称(完整)。格式(“%tA”、校准、校准);星期二本地化月份名称(缩写)。格式(“%tb”,cal);aprtb本地化月份名称(完整)。格式(“%tB”,cal);ApriltcC库asctime(3)类输出。不要使用。格式(“%tc”,cal);4月1日星期二16:19:17 CEST 2008tC2数字世纪。格式(“%tC”,cal);20td2位月日(01-31)。格式(“%td”,cal);01TDUS日期格式(年月日)。不要使用。格式(“%tD”,cal);08年1月4日(1-31日)。格式(“%te”,cal);1 ISO 8601格式的完整日期(YYYY-MM-DD)。格式(“%tF”,cal);2008年04月01日%tb的同义词。tH2位数字24小时制(00-23)。格式(“%tH”,cal);16tI2数字12小时(01-12)。格式(“%tI”,cal);04tj3数字日期(001-366)。格式(“%tj”,cal);092tk24小时(0-23)。格式(“%tk”,cal);16tl12一天中的小时数(1-12)。格式(“%tl”,cal);4毫秒。格式(“%tL”,cal);359tm2位年份月份(01-12)。格式(“%tm”,cal);04tM2位分钟。格式(“%tM”,cal);08tn纳秒。格式(“%tN”,cal);35900万吨/年。m、 或p.m.格式(“%tp%tp”,cal,cal);从新纪元开始,pm PMTQ为毫秒。格式(“%tQ”,cal);1207059412656TR完整的12小时时间(%tI:%tM:%tS%Tp)。格式(“%tr”,cal);04:15:32 pmtr短24小时时间(%tH:%tM)。格式(“%tR”,cal);16:15秒,从大纪元开始。格式(“%ts”,cal);1207059412tS2位秒(00-60)。格式(“%tS”,cal);17t全天候(%tH:%tM:%tS)。格式(“%tT”,cal);16:15:32ty2位年份(00-99)。格式(“%ty”,cal);08tY4位年份。格式(“%tY”,cal);2008TZ时区GMT偏移量。格式(“%tz”,cal)+0100TZ本地化时区缩写。格式(“%tZ”,cal);塞斯特
与其他转换一样,日期/时间转换采用大写格式。根据格式化程序区域设置的规则,将%t替换为%t将使字段大写。
数字本地化。有些转换使用本地化的十进制数字,而不是通常的ASCII数字。因此,将123格式化为%d将在英语地区给出123,但在适当的阿拉伯语地区给出123。十进制整数转换%d、浮点转换%e、%f和%g以及所有日期/时间%t或%t转换都会发生此数字本地化,但不会发生其他转换。
线程安全。格式化程序不是线程安全的。
代码示例来源:origin: stackoverflow.com
public String toDecimalString() {
Formatter f = new Formatter();
f.format("%d", digits[0]);
for(int i = 1 ; i < digits.length; i++) {
f.format("%09d", digits[i]);
}
return f.toString();
}
代码示例来源:origin: org.assertj/assertj-core
private static String escapeUnicode(String input) {
StringBuilder b = new StringBuilder(input.length());
Formatter formatter = new Formatter(b);
for (char c : input.toCharArray()) {
if (c < 128) {
b.append(c);
} else {
formatter.format("\\u%04x", (int) c);
}
}
formatter.close();
return b.toString();
}
}
代码示例来源:origin: knowm/XChange
private static String byteToHex(final byte[] hash) {
Formatter formatter = new Formatter();
for (byte b : hash) {
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
}
代码示例来源:origin: org.codehaus.groovy/groovy
private static void callWithFormatter(Closure closure, Formatter formatter) {
try {
closure.call(formatter);
} finally {
formatter.flush();
formatter.close();
}
}
代码示例来源:origin: Unidata/thredds
private String debugMissingVar(NetcdfFile proto, NetcdfFile result) {
Formatter f = new Formatter();
f.format("%nresult dataset %s%n", result.getLocation());
for (Variable v: result.getVariables())
f.format(" %s%n", v.getNameAndDimensions());
f.format("%n");
f.format("proto dataset %s%n", proto.getLocation());
for (Variable v: proto.getVariables())
f.format(" %s%n", v.getNameAndDimensions());
return f.toString();
}
代码示例来源:origin: edu.ucar/netcdf
public String toString() {
Formatter sbuff = new Formatter();
sbuff.format("refno=%d name=%s fillValue=%s %n", refno, v.getShortName(), fillValue);
sbuff.format(" isChunked=%s isCompressed=%s isLinked=%s hasNoData=%s %n", isChunked, isCompressed, isLinked, hasNoData);
sbuff.format(" elemSize=%d data start=%d length=%s %n%n", elemSize, start, length);
for (Tag t : tags)
sbuff.format(" %s%n", t.detail());
return sbuff.toString();
}
代码示例来源:origin: edu.ucar/bufr
private void writeFloat(Variable v, double val) throws XMLStreamException {
Attribute bitWidthAtt = v.findAttribute("BUFR:bitWidth");
int sigDigits;
if (bitWidthAtt == null)
sigDigits = 7;
else {
int bitWidth = bitWidthAtt.getNumericValue().intValue();
if (bitWidth < 30) {
double sigDigitsD = Math.log10(2 << bitWidth);
sigDigits = (int) (sigDigitsD + 1);
} else {
sigDigits = 7;
}
}
Formatter stringFormatter = new Formatter();
String format = "%." + sigDigits + "g";
stringFormatter.format(format, val);
staxWriter.writeCharacters(stringFormatter.toString());
}
代码示例来源:origin: edu.ucar/cdm
/**
* String representation of Variable and its attributes.
*/
public String toStringDebug() {
Formatter f = new Formatter();
f.format("Variable %s", getFullName());
if (ncfile != null) {
f.format(" in file %s", getDatasetLocation());
String extra = ncfile.toStringDebug(this);
if (extra != null)
f.format(" %s", extra);
}
return f.toString();
}
代码示例来源:origin: edu.ucar/netcdf
/**
* String representation of Variable and its attributes.
*/
public String toStringDebug() {
Formatter f = new Formatter();
f.format("Variable %s", getFullName());
if (ncfile != null) {
f.format(" in file %s", ncfile.getLocation());
String extra = ncfile.toStringDebug(this);
if (extra != null)
f.format(" %s", extra);
}
return f.toString();
}
代码示例来源:origin: edu.ucar/netcdf
public void augmentDataset(NetcdfDataset ds, CancelTask cancelTask) throws IOException {
NcMLReader.wrapNcMLresource(ds, CoordSysBuilder.resourcesDir + "Zebra.ncml", cancelTask);
// special time handling
// the time coord var is created in the NcML
// set its values = base_time + time_offset(time)
Dimension timeDim = ds.findDimension("time");
Variable base_time = ds.findVariable("base_time");
Variable time_offset = ds.findVariable("time_offset");
Variable time = ds.findVariable("time");
if ((timeDim == null) || (base_time == null) || (time_offset == null) || (time == null))
return;
Attribute att = base_time.findAttribute(CDM.UNITS);
String units = (att != null) ? att.getStringValue() : "seconds since 1970-01-01 00:00 UTC";
time.addAttribute(new Attribute(CDM.UNITS, units));
Array data;
try {
double baseValue = base_time.readScalarDouble();
data = time_offset.read();
IndexIterator iter = data.getIndexIterator();
while (iter.hasNext())
iter.setDoubleCurrent(iter.getDoubleNext() + baseValue);
} catch (java.io.IOException ioe) {
parseInfo.format("ZebraConvention failed to create time Coord Axis for file %s err= %s\n", ds.getLocation(), ioe);
return;
}
time.setCachedData(data, true);
}
代码示例来源:origin: Unidata/thredds
private void createNewVariables(NetcdfDataset ds, Variable ncVar, List<Dimension> newDims,
Dimension levelDim) throws InvalidRangeException {
List<Dimension> dims = ncVar.getDimensions();
int newDimIndex = dims.indexOf(levelDim);
//String shapeS = ncVar.getShapeS();
int[] origin = new int[ncVar.getRank()];
int[] shape = ncVar.getShape();
int count = 0;
for (Dimension dim : newDims) {
String name = ncVar.getShortName() + "-" + dim.getShortName();
origin[newDimIndex] = count;
shape[newDimIndex] = dim.getLength();
Variable varNew = ncVar.section(new Section(origin, shape));
varNew.setName(name);
varNew.setDimension(newDimIndex, dim);
// synthesize long name
String long_name = ds.findAttValueIgnoreCase(ncVar, CDM.LONG_NAME, ncVar.getShortName());
long_name = long_name + "-" + dim.getShortName();
ds.addVariableAttribute(varNew, new Attribute(CDM.LONG_NAME, long_name));
ds.addVariable(null, varNew);
parseInfo.format("Created New Variable as section = ");
varNew.getNameAndDimensions(parseInfo, true, false);
parseInfo.format("%n");
count += dim.getLength();
}
}
代码示例来源:origin: edu.ucar/netcdf
public void augmentDataset( NetcdfDataset ds, CancelTask cancelTask) throws IOException {
if (null != ds.findVariable("xCoord")) return; // check if its already been done - aggregating enhanced datasets.
parseInfo.format("IFPS augmentDataset \n");
Variable lonVar = ds.findVariable("longitude");
lonVar.addAttribute( new Attribute(CDM.UNITS, CDM.LON_UNITS));
lonVar.addAttribute( new Attribute(_Coordinate.AxisType, AxisType.Lon.toString()));
Variable latVar = ds.findVariable("latitude");
latVar.addAttribute( new Attribute(_Coordinate.AxisType, AxisType.Lat.toString()));
latVar.addAttribute( new Attribute(CDM.UNITS, CDM.LAT_UNITS));
for (Variable ncvar : vars) {
if ((!ncvar.getDimension(0).getShortName().equals("DIM_0")) && !ncvar.getShortName().endsWith("History")
&& (ncvar.getRank() > 2) && !ncvar.getShortName().startsWith("Tool")) {
createTimeCoordinate(ds, ncvar);
代码示例来源:origin: edu.ucar/netcdf
if (null != (dim = ds.getRootGroup().findDimension(name))) {
if (dim.getLength() == len) {
Variable coord = ds.getRootGroup().findVariable(name);
Array coordData = coord.read();
Array newData = Array.makeArray(coord.getDataType(), values);
if (MAMath.isEqual(coordData, newData)) {
if (debugBreakup) parseInfo.format(" use existing coord %s\n", dim);
while (ds.getRootGroup().findDimension(name) != null) {
name = orgName + "-" + count;
count++;
dim = new Dimension(name, len);
ds.addDimension(null, dim);
if (debugBreakup) parseInfo.format(" make Dimension = %s length = %d\n", name, len);
String positive = getZisPositive(ds, v);
if (null != positive)
v.addAttribute(new Attribute(_Coordinate.ZisPositive, positive));
ds.setValues(v, values);
ds.addCoordinateAxis(v);
parseInfo.format("Created Z Coordinate Axis = ");
v.getNameAndDimensions(parseInfo, true, false);
parseInfo.format("\n");
代码示例来源:origin: edu.ucar/cdm
private CoordinateAxis makeTimeCoordAxisFromReference(NetcdfDataset ds, Variable timeVar, Array vals) {
Variable refVar = ds.findVariable("reftime");
if (refVar == null) return null;
double refValue;
try {
Array refArray = refVar.read();
refValue = refArray.getDouble(refArray.getIndex()); // get the first value
} catch (IOException ioe) {
return null;
}
// construct the values array - make it a double to be safe
Array dvals = Array.factory(double.class, vals.getShape());
IndexIterator diter = dvals.getIndexIterator();
IndexIterator iiter = vals.getIndexIterator();
while (iiter.hasNext())
diter.setDoubleNext(iiter.getDoubleNext() + refValue); // add reftime to each of the values
String units = ds.findAttValueIgnoreCase(refVar, CDM.UNITS, "seconds since 1970-1-1 00:00:00");
units = normalize(units);
String desc = "synthesized time coordinate from reftime, valtimeMINUSreftime";
CoordinateAxis1D timeCoord = new CoordinateAxis1D(ds, null, "timeCoord", DataType.DOUBLE, "record", units, desc);
timeCoord.setCachedData(dvals, true);
parseInfo.format("Created Time Coordinate Axis From Reference = ");
timeCoord.getNameAndDimensions(parseInfo, true, false);
parseInfo.format("%n");
return timeCoord;
}
代码示例来源:origin: edu.ucar/netcdf
private CoordinateAxis makeTimeCoordAxis(NetcdfDataset ds) {
Variable timeVar = ds.findVariable("valtimeMINUSreftime");
Dimension recordDim = ds.findDimension("record");
Array vals;
vals = timeVar.read();
} catch (IOException ioe) {
return null;
int recLen = recordDim.getLength();
int valLen = (int) vals.getSize();
if (recLen != valLen) {
try {
vals = vals.sectionNoReduce(new int[]{0}, new int[]{recordDim.getLength()}, null);
parseInfo.format(" corrected the TimeCoordAxis length\n");
} catch (InvalidRangeException e) {
parseInfo.format("makeTimeCoordAxis InvalidRangeException\n");
String units = makeTimeUnitFromFilename(ds.getLocation());
if (units == null) // ok that didnt work, try something else
return makeTimeCoordAxisFromReference(ds, timeVar, vals);
parseInfo.format("Created Time Coordinate Axis = ");
timeCoord.getNameAndDimensions(parseInfo, true, false);
parseInfo.format("\n");
代码示例来源:origin: org.apache.commons/commons-lang3
@Test
public void testDefaultAppend() {
assertEquals("foo", FormattableUtils.append("foo", new Formatter(), 0, -1, -1).toString());
assertEquals("fo", FormattableUtils.append("foo", new Formatter(), 0, -1, 2).toString());
assertEquals(" foo", FormattableUtils.append("foo", new Formatter(), 0, 4, -1).toString());
assertEquals(" foo", FormattableUtils.append("foo", new Formatter(), 0, 6, -1).toString());
assertEquals(" fo", FormattableUtils.append("foo", new Formatter(), 0, 3, 2).toString());
assertEquals(" fo", FormattableUtils.append("foo", new Formatter(), 0, 5, 2).toString());
assertEquals("foo ", FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 4, -1).toString());
assertEquals("foo ", FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 6, -1).toString());
assertEquals("fo ", FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 3, 2).toString());
assertEquals("fo ", FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 5, 2).toString());
}
代码示例来源:origin: edu.ucar/cdm
private void compareVariableData(Variable var1, Variable var2, boolean showCompare, boolean justOne) throws IOException {
Array data1 = var1.read();
Array data2 = var2.read();
if (showCompare)
f.format(" compareArrays %s unlimited=%s size=%d%n", var1.getNameAndDimensions(), var1.isUnlimited(), data1.getSize());
compareData(var1.getFullName(), data1, data2, justOne);
if (showCompare) f.format(" ok%n");
}
代码示例来源:origin: Unidata/thredds
private void readAtt(Object parent, Element attElem) {
String name = attElem.getAttributeValue("name");
if (name == null) {
errlog.format("NcML Attribute name is required (%s)%n", attElem);
return;
}
try {
ucar.ma2.Array values = NcMLReader.readAttributeValues(attElem);
Attribute att = new ucar.nc2.Attribute(name, values);
if (parent instanceof Group)
((Group) parent).addAttribute(att);
else if (parent instanceof Variable)
((Variable) parent).addAttribute(att);
} catch (RuntimeException e) {
errlog.format("NcML new Attribute Exception: %s att=%s in=%s%n", e.getMessage(), name, parent);
}
}
代码示例来源:origin: edu.ucar/netcdf
public void showCompress(Formatter f) throws IOException {
NetcdfFile ncfile = iosp.getNetcdfFile();
Size totalSize = new Size(0,0);
for (Variable v : ncfile.getVariables()) {
H5header.Vinfo vinfo = (H5header.Vinfo) v.getSPobject();
showCompress(v, vinfo, totalSize, f);
}
f.format("%n");
f.format(" total bytes = %d%n", totalSize.nominal);
f.format(" total storage = %d%n", totalSize.storage);
f.format(" compression = %f%n", totalSize.getRatio());
f.format(" nchunks = %d%n", totalSize.count);
File raf = new File(ncfile.getLocation());
f.format(" file size = %d%n", raf.length());
f.format(" overhead = %f%n", ((float) raf.length()/totalSize.storage));
}
代码示例来源:origin: edu.ucar/netcdf
private double findAttributeDouble(NetcdfDataset ds, String attname) {
Attribute att = ds.findGlobalAttributeIgnoreCase(attname);
if (att == null) {
parseInfo.format("ERROR cant find attribute= %s\n", attname);
return Double.NaN;
}
return att.getNumericValue().doubleValue();
}
内容来源于网络,如有侵权,请联系作者删除!