下面列出了java.util.Formatter#toString ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static String formatEntry(OLogEntryDescription entry) {
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb, Locale.US);
formatter.format(" [term: %" + LONG_DIGITS + "d]", entry.getElectionTerm());
formatter.format(" [seq: %" + LONG_DIGITS + "d]", entry.getSeqNum());
formatContent(formatter, entry);
if (!entry.isHeaderCrcValid()) {
formatter.format(" <invalid header CRC>");
}
if (!entry.isContentCrcValid()) {
formatter.format(" <invalid content CRC>");
}
return formatter.toString();
}
public static String SHA1(InputStream is) {
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
for (int read; (read = is.read(buffer)) != -1; ) {
messageDigest.update(buffer, 0, read);
}
Formatter formatter = new Formatter();
// Convert the byte to hex format
for (final byte b : messageDigest.digest()) {
formatter.format("%02x", b);
}
return formatter.toString();
} catch (NoSuchAlgorithmException | IOException e) {
android.util.Log.e(TAG,e.getMessage());
} finally {
YTutils.close(is);
}
return null;
}
void writeHeader(PointFeature pf) throws IOException {
List<VariableSimpleIF> coords = new ArrayList<>();
coords.add(VariableSimpleBuilder.makeScalar(timeName, "time of measurement", timeUnit.getUdUnit(), DataType.DOUBLE)
.addAttribute(CF.CALENDAR, timeUnit.getCalendar().toString()).build());
coords.add(
VariableSimpleBuilder.makeScalar(latName, "latitude of measurement", CDM.LAT_UNITS, DataType.DOUBLE).build());
coords.add(
VariableSimpleBuilder.makeScalar(lonName, "longitude of measurement", CDM.LON_UNITS, DataType.DOUBLE).build());
Formatter coordNames = new Formatter().format("%s %s %s", timeName, latName, lonName);
if (altUnits != null) {
coords.add(VariableSimpleBuilder.makeScalar(altName, "altitude of measurement", altUnits, DataType.DOUBLE)
.addAttribute(CF.POSITIVE, CF1Convention.getZisPositive(altName, altUnits)).build());
coordNames.format(" %s", altName);
}
super.writeHeader(coords, null, null, pf.getDataAll(), coordNames.toString());
}
@Override
public String toString() {
// Output into coordinate format. Indices start from 1 instead of 0
Formatter out = new Formatter();
out.format("%10d %19d\n", size, Matrices.cardinality(this));
int i = 0;
for (VectorEntry e : this) {
if (e.get() != 0)
out.format("%10d % .12e\n", e.index() + 1, e.get());
if (++i == 100) {
out.format("...\n");
break;
}
}
return out.toString();
}
/**
* Generates a label for the specified data item.
*
* @param dataset the dataset ({@code null} not permitted).
* @param seriesKey the series key ({@code null} not permitted).
*
* @return The series label (possibly {@code null}).
*/
@Override @SuppressWarnings("unchecked")
public String generateItemLabel(XYZDataset dataset,
Comparable<?> seriesKey, int itemIndex) {
Args.nullNotPermitted(dataset, "dataset");
Args.nullNotPermitted(seriesKey, "seriesKey");
if (this.itemSelection != null) {
XYZItemKey key = new XYZItemKey(seriesKey, itemIndex);
if (!this.itemSelection.isSelected(key)) {
return null;
}
}
int seriesIndex = dataset.getSeriesIndex(seriesKey);
Formatter formatter = new Formatter(new StringBuilder());
double x = dataset.getX(seriesIndex, itemIndex);
double y = dataset.getY(seriesIndex, itemIndex);
double z = dataset.getZ(seriesIndex, itemIndex);
formatter.format(this.template, seriesKey, x, y, z);
String result = formatter.toString();
formatter.close();
return result;
}
/**
* Publishes a value on MQTT. A command topic needs to be set in the configuration.
*
* @param command The command to send
* @return A future that completes with true if the publishing worked and false and/or exceptionally otherwise.
*/
public CompletableFuture<@Nullable Void> publishValue(Command command) {
cachedValue.update(command);
String mqttCommandValue = cachedValue.getMQTTpublishValue();
final MqttBrokerConnection connection = this.connection;
if (!readOnly && connection != null) {
// Formatter: Applied before the channel state value is published to the MQTT broker.
if (config.formatBeforePublish.length() > 0) {
try (Formatter formatter = new Formatter()) {
Formatter format = formatter.format(config.formatBeforePublish, mqttCommandValue);
mqttCommandValue = format.toString();
} catch (IllegalFormatException e) {
logger.debug("Format pattern incorrect for {}", channelUID, e);
}
}
// Outgoing transformations
for (ChannelStateTransformation t : transformationsOut) {
mqttCommandValue = t.processValue(mqttCommandValue);
}
// Send retained messages if this is a stateful channel
return connection.publish(config.commandTopic, mqttCommandValue.getBytes(), 1, config.retained)
.thenRun(() -> {
});
} else {
CompletableFuture<@Nullable Void> f = new CompletableFuture<>();
f.completeExceptionally(new IllegalStateException("No connection or readOnly channel!"));
return f;
}
}
/**
*
*/
public void setDataset(NetcdfDataset newds) {
if (newds == null) {
return;
}
try {
if (ds != null) {
ds.close();
}
} catch (IOException ioe) {
logger.warn("close failed");
}
Formatter parseInfo = new Formatter();
this.ds = newds;
try {
sgTable.setDataset(newds, parseInfo);
} catch (IOException e) {
String info = parseInfo.toString();
if (!info.isEmpty()) {
detailTA.setText(info);
detailWindow.show();
}
e.printStackTrace();
return;
}
setSelectedItem(newds.getLocation());
}
@Override
public String toString(Object o, String formatString, Locale locale) {
// o will be instanceof Number
if ( formatString==null ) return o.toString();
Formatter f = new Formatter(locale);
f.format(formatString, o);
return f.toString();
}
public static String toHex(final byte[] bytes) {
Formatter formatter = new Formatter();
for (byte b : bytes) {
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
private static String byteArray2Hex(final byte[] hash) {
Formatter formatter = new Formatter();
try {
for (byte b : hash) {
formatter.format("%02x", b);
}
return formatter.toString();
} finally {
formatter.close();
}
}
String getDatasetInfo() {
if (null == gridDataset)
return "";
Formatter info = new Formatter();
gridDataset.getDetailInfo(info);
return info.toString();
}
public String runClassifier() {
Formatter ff = new Formatter();
String type = null;
try (NetcdfDataset ds = NetcdfDatasets.openDataset(f.getPath())) {
type = DtCoverageCSBuilder.describe(ds, ff);
} catch (IOException e) {
StringWriter sw = new StringWriter(10000);
e.printStackTrace(new PrintWriter(sw));
ff.format("%n%s", sw.toString());
}
ff.format("CoverageCS.Type = %s", type);
return ff.toString();
}
/** Print StructureData to returned String. */
public static String printStructureData(StructureData sdata) {
Formatter out = new Formatter();
for (StructureMembers.Member m : sdata.getMembers()) {
Array memData = sdata.getArray(m);
if (memData instanceof ArrayChar) {
out.format("%s", ((ArrayChar) memData).getString());
} else {
printArray(out, memData, null, null, new Indent(2), null, true);
}
out.format(",");
}
return out.toString();
}
private static String byteArray2Hex(final byte[] hash) {
Formatter formatter = new Formatter();
for (byte b : hash) {
formatter.format("%02x", b);
}
return formatter.toString();
}
private void checkBetAmount(BigDecimal betAmount) {
if (BigDecimal.ZERO.compareTo(betAmount) >= 0) {
Formatter formatter = new Formatter(Locale.US).format(
"Invalid bet amount <%.2f>. Please place a bet of more than 0",
betAmount
);
throw new IllegalArgumentException(formatter.toString());
}
}
Row(GridDatatype gg) {
this.gg = gg;
Formatter f = new Formatter();
for (Dimension dim : gg.getDimensions())
f.format("%s ", dim.getShortName());
dims = f.toString();
}
private String wordProbToString(double[] prob) {
Formatter formatter = new Formatter();
for(int j=0;j<prob.length;++j) {
double p = prob[j];
if (p>=0.00001) {
formatter.format(" %s:%.5f", langlist.get(j), p);
}
}
formatter.close();
return formatter.toString();
}
private static void doit(String spec, String filterExpect) {
Formatter errlog = new Formatter();
CollectionSpecParser specp = new CollectionSpecParser(spec, errlog);
System.out.printf("spec= %s%n%s%n", spec, specp);
String err = errlog.toString();
System.out.printf("-----------------------------------%n");
String filterHave = (specp.getFilter() != null) ? specp.getFilter().toString() : "null";
assertThat(filterHave).isEqualTo(filterExpect);
}
private String getDecl(Variable ve) {
Formatter sb = new Formatter();
sb.format("%s ", ve.getDataType().toString());
ve.getNameAndDimensions(sb, true, true);
return sb.toString();
}
/**
* Print a section of the data of the given Variable.
*
* @param v variable to print
* @param sectionSpec string specification
* @param ct allow task to be cancelled; may be null.
* @return String result formatted data ouptut
* @throws IOException on write error
* @throws InvalidRangeException is specified section doesnt match variable shape
*/
private static String printVariableDataSection(Variable v, String sectionSpec, CancelTask ct)
throws IOException, InvalidRangeException {
Array data = v.read(sectionSpec);
Formatter out = new Formatter();
printArray(out, data, v.getFullName(), new Indent(2), ct);
return out.toString();
}