下面列出了java.util.Formatter#close ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static String stringForTimeNoHour(long timeMs) {
String formatter;
StringBuilder formatBuilder = new StringBuilder();
Formatter formatter2 = new Formatter(formatBuilder, Locale.getDefault());
if (timeMs >= 0) {
try {
int totalSeconds = (int) (timeMs / 1000);
int seconds = totalSeconds % 60;
int minutes = totalSeconds / 60;
formatBuilder.setLength(0);
formatter = formatter2.format("%02d:%02d", new Object[]{Integer.valueOf(minutes), Integer.valueOf(seconds)}).toString();
} finally {
formatter2.close();
}
} else {
formatter = "00:00";
formatter2.close();
}
return formatter;
}
public void exportValues(final StringBuilder result) {
Formatter formatter = new Formatter(result);
formatter.format("%s: %s\n", BundleUtil.getString(Bundle.ACADEMIC, "label.IndividualCandidacy.candidacy"),
getCandidacyExecutionInterval().getName());
formatter.format("%s: %s\n", BundleUtil.getString(Bundle.ACADEMIC, "label.IndividualCandidacy.state"), getState()
.getLocalizedName());
formatter.format("%s: %s\n", BundleUtil.getString(Bundle.ACADEMIC, "label.IndividualCandidacy.whenCreated"),
getWhenCreated().toString("yyy-MM-dd"));
formatter.format("%s: %s\n", BundleUtil.getString(Bundle.ACADEMIC, "label.IndividualCandidacy.candidacyDate"),
getCandidacyDate().toString());
formatter.format("%s: %s\n", BundleUtil.getString(Bundle.ACADEMIC, "label.IndividualCandidacy.responsible"),
StringUtils.isEmpty(getResponsible()) ? StringUtils.EMPTY : getResponsible());
formatter.format("%s: %s\n", BundleUtil.getString(Bundle.ACADEMIC, "label.IndividualCandidacy.notes"),
StringUtils.isEmpty(getNotes()) ? StringUtils.EMPTY : getNotes());
formatter.format("%s: %s\n", BundleUtil.getString(Bundle.ACADEMIC, "label.IndividualCandidacy.observations"),
StringUtils.isEmpty(getObservations()) ? StringUtils.EMPTY : getObservations());
for (final Formation formation : getFormationsSet()) {
formation.exportValues(result);
}
formatter.close();
}
public String toString() {
StringBuilder sb = new StringBuilder(1024);
Formatter fm = new Formatter(sb);
if (creationTime() != null)
fm.format(" creationTime : %tc%n", creationTime().toMillis());
else
fm.format(" creationTime : null%n");
if (lastAccessTime() != null)
fm.format(" lastAccessTime : %tc%n", lastAccessTime().toMillis());
else
fm.format(" lastAccessTime : null%n");
fm.format(" lastModifiedTime: %tc%n", lastModifiedTime().toMillis());
fm.format(" isRegularFile : %b%n", isRegularFile());
fm.format(" isDirectory : %b%n", isDirectory());
fm.format(" isSymbolicLink : %b%n", isSymbolicLink());
fm.format(" isOther : %b%n", isOther());
fm.format(" fileKey : %s%n", fileKey());
fm.format(" size : %d%n", size());
fm.format(" compressedSize : %d%n", compressedSize());
fm.format(" crc : %x%n", crc());
fm.format(" method : %d%n", method());
fm.close();
return sb.toString();
}
public void setVisualPrecision(int precision) {
StringBuilder builder = new StringBuilder();
double roundedValue = DataStructureUtils.roundToPowerOf10(getValue(), precision);
Formatter formatter = new Formatter(builder, Locale.getDefault());
String format;
if (precision < 0) {
format = "%." + -precision + "f";
} else {
format = "%.0f";
}
formatter.format(format, roundedValue);
formatter.close();
valueString = builder.toString();
}
@Override
public String toString() {
Formatter formatter = new Formatter();
int row = 0;
for (Codeword codeword : codewords) {
if (codeword == null) {
formatter.format("%3d: | %n", row++);
continue;
}
formatter.format("%3d: %3d|%3d%n", row++, codeword.getRowNumber(), codeword.getValue());
}
String result = formatter.toString();
formatter.close();
return result;
}
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;
}
/**
* Generates a series label.
*
* @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
public <S extends Comparable<S>> String generateSeriesLabel(
XYZDataset<S> dataset, S seriesKey) {
Args.nullNotPermitted(dataset, "dataset");
Args.nullNotPermitted(seriesKey, "seriesKey");
Formatter formatter = new Formatter(new StringBuilder());
int count = dataset.getItemCount(dataset.getSeriesIndex(seriesKey));
double total = DataUtils.total(dataset, seriesKey);
formatter.format(this.template, seriesKey, count, total);
String result = formatter.toString();
formatter.close();
return result;
}
@Override
public void printf(String format, Object value) {
StringBuilder builder = new StringBuilder(128);
builder.append(getId()).append(" : ");
Formatter formatter = new Formatter(builder);
formatter.format(Locale.getDefault(), format, value);
formatter.close();
logger.info(builder.toString());
}
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();
}
}
public static String toHexString(byte[] bytes, String sep) {
Formatter f = new Formatter();
for (int i = 0; i < bytes.length; i++) {
f.format("%02x", bytes[i]);
if (i < bytes.length - 1) {
f.format(sep);
}
}
String result = f.toString();
f.close();
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb);
String rv = formatter.format(Locale.US, "%s[x1=%f y1=%f x2=%f y2=%f]", this.getClass().toString(), this.x1, this.y1, this.x2, this.y2).toString();
formatter.close();
return rv;
}
private void writeSingleInteger(String fmt, int num, StringBuffer output, List<Special> numSpecials, Set<CellNumberStringMod> mods) {
StringBuffer sb = new StringBuffer();
Formatter formatter = new Formatter(sb, locale);
try {
formatter.format(locale, fmt, num);
} finally {
formatter.close();
}
writeInteger(sb, output, numSpecials, mods, false);
}
private String bytesToHex(byte[] hash) {
Formatter formatter = new Formatter();
for (byte b : hash) {
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
@Override
public String toString() {
DetectionResultColumn rowIndicatorColumn = detectionResultColumns[0];
if (rowIndicatorColumn == null) {
rowIndicatorColumn = detectionResultColumns[barcodeColumnCount + 1];
}
Formatter formatter = new Formatter();
for (int codewordsRow = 0; codewordsRow < rowIndicatorColumn.getCodewords().length; codewordsRow++) {
formatter.format("CW %3d:", codewordsRow);
for (int barcodeColumn = 0; barcodeColumn < barcodeColumnCount + 2; barcodeColumn++) {
if (detectionResultColumns[barcodeColumn] == null) {
formatter.format(" | ");
continue;
}
Codeword codeword = detectionResultColumns[barcodeColumn].getCodewords()[codewordsRow];
if (codeword == null) {
formatter.format(" | ");
continue;
}
formatter.format(" %3d|%3d", codeword.getRowNumber(), codeword.getValue());
}
formatter.format("%n");
}
String result = formatter.toString();
formatter.close();
return result;
}
@Override
public void exportValues(StringBuilder result) {
super.exportValues(result);
Formatter formatter = new Formatter(result);
formatter.format("%s: %s\n", BundleUtil.getString(Bundle.CANDIDATE, "label.process.id"), getCandidacyProcess()
.getProcessCode());
PrecedentDegreeInformation precedentDegreeInformation = getCandidacyProcess().getPrecedentDegreeInformation();
formatter.format("%s: %s\n",
BundleUtil.getString(Bundle.ACADEMIC, "label.SecondCycleIndividualCandidacy.previous.degree"),
precedentDegreeInformation.getPrecedentDegreeDesignation());
formatter.format("%s: %s\n", BundleUtil.getString(Bundle.ACADEMIC, "label.SecondCycleIndividualCandidacy.institution"),
precedentDegreeInformation.getPrecedentInstitution().getName());
formatter.format("%s: %s\n",
BundleUtil.getString(Bundle.APPLICATION, "label.candidacy.numberOfEnroledCurricularCourses"),
precedentDegreeInformation.getNumberOfEnroledCurricularCourses());
formatter.format("%s: %s\n",
BundleUtil.getString(Bundle.APPLICATION, "label.candidacy.numberOfApprovedCurricularCourses"),
precedentDegreeInformation.getNumberOfApprovedCurricularCourses());
formatter.format("%s: %s\n", BundleUtil.getString(Bundle.APPLICATION, "label.candidacy.gradeSum"),
precedentDegreeInformation.getGradeSum());
formatter.format("%s: %s\n", BundleUtil.getString(Bundle.APPLICATION, "label.candidacy.approvedEcts"),
precedentDegreeInformation.getApprovedEcts());
formatter.format("%s: %s\n", BundleUtil.getString(Bundle.APPLICATION, "label.candidacy.enroledEcts"),
precedentDegreeInformation.getEnroledEcts());
formatter.format("\n");
formatter.format("%s: %f\n", BundleUtil.getString(Bundle.ACADEMIC, "label.SecondCycleIndividualCandidacy.affinity"),
getAffinity() != null ? getAffinity() : BigDecimal.ZERO);
formatter.format("%s: %d\n", BundleUtil.getString(Bundle.ACADEMIC, "label.SecondCycleIndividualCandidacy.degreeNature"),
getDegreeNature() != null ? getDegreeNature() : 0);
formatter.format("%s: %f\n",
BundleUtil.getString(Bundle.ACADEMIC, "label.DegreeChangeIndividualCandidacy.approvedEctsRate"),
getApprovedEctsRate() != null ? getApprovedEctsRate() : BigDecimal.ZERO);
formatter.format("%s: %f\n", BundleUtil.getString(Bundle.ACADEMIC, "label.DegreeChangeIndividualCandidacy.gradeRate"),
getGradeRate() != null ? getGradeRate() : BigDecimal.ZERO);
formatter.format("%s: %f\n",
BundleUtil.getString(Bundle.ACADEMIC, "label.SecondCycleIndividualCandidacy.seriesCandidacyGrade"),
getSeriesCandidacyGrade() != null ? getSeriesCandidacyGrade() : BigDecimal.ZERO);
formatter.close();
}
public String toString() {
StringBuilder compliantBlocksSB = new StringBuilder();
compliantBlocksSB.append("\nBlocks satisfying the specified storage policy:");
compliantBlocksSB.append("\nStorage Policy # of blocks % of blocks\n");
StringBuilder nonCompliantBlocksSB = new StringBuilder();
Formatter compliantFormatter = new Formatter(compliantBlocksSB);
Formatter nonCompliantFormatter = new Formatter(nonCompliantBlocksSB);
NumberFormat percentFormat = NumberFormat.getPercentInstance();
percentFormat.setMinimumFractionDigits(4);
percentFormat.setMaximumFractionDigits(4);
for (Map.Entry<StorageTypeAllocation, Long> storageComboCount:
sortByComparator(storageComboCounts)) {
double percent = (double) storageComboCount.getValue() /
(double) totalBlocks;
StorageTypeAllocation sta = storageComboCount.getKey();
if (sta.policyMatches()) {
compliantFormatter.format("%-25s %10d %20s%n",
sta.getStoragePolicyDescriptor(),
storageComboCount.getValue(),
percentFormat.format(percent));
} else {
if (nonCompliantBlocksSB.length() == 0) {
nonCompliantBlocksSB.append("\nBlocks NOT satisfying the specified storage policy:");
nonCompliantBlocksSB.append("\nStorage Policy ");
nonCompliantBlocksSB.append(
"Specified Storage Policy # of blocks % of blocks\n");
}
nonCompliantFormatter.format("%-35s %-20s %10d %20s%n",
sta.getStoragePolicyDescriptor(),
sta.getSpecifiedStoragePolicy().getName(),
storageComboCount.getValue(),
percentFormat.format(percent));
}
}
if (nonCompliantBlocksSB.length() == 0) {
nonCompliantBlocksSB.append("\nAll blocks satisfy specified storage policy.\n");
}
compliantFormatter.close();
nonCompliantFormatter.close();
return compliantBlocksSB.toString() + nonCompliantBlocksSB;
}
/** {@inheritDoc} */
public void formatValue(StringBuffer toAppendTo, Object value) {
if (value == null)
value = 0.0;
if (value instanceof Number) {
Number num = (Number) value;
long v = num.longValue();
if (v == 0L) {
value = EXCEL_EPOCH_CAL.getTime();
} else {
Calendar c = (Calendar)EXCEL_EPOCH_CAL.clone();
c.add(Calendar.SECOND, (int)(v / 1000));
c.add(Calendar.MILLISECOND, (int)(v % 1000));
value = c.getTime();
}
}
AttributedCharacterIterator it = dateFmt.formatToCharacterIterator(value);
boolean doneAm = false;
boolean doneMillis = false;
it.first();
for (char ch = it.first();
ch != CharacterIterator.DONE;
ch = it.next()) {
if (it.getAttribute(DateFormat.Field.MILLISECOND) != null) {
if (!doneMillis) {
Date dateObj = (Date) value;
int pos = toAppendTo.length();
Formatter formatter = new Formatter(toAppendTo, Locale.ROOT);
try {
long msecs = dateObj.getTime() % 1000;
formatter.format(locale, sFmt, msecs / 1000.0);
} finally {
formatter.close();
}
toAppendTo.delete(pos, pos + 2);
doneMillis = true;
}
} else if (it.getAttribute(DateFormat.Field.AM_PM) != null) {
if (!doneAm) {
if (showAmPm) {
if (amPmUpper) {
toAppendTo.append(Character.toUpperCase(ch));
if (showM)
toAppendTo.append('M');
} else {
toAppendTo.append(Character.toLowerCase(ch));
if (showM)
toAppendTo.append('m');
}
}
doneAm = true;
}
} else {
toAppendTo.append(ch);
}
}
}
/**
* Writes the model to the modelOutput. It uses {@link java.util.Locale#ENGLISH} for number
* formatting.
*
* <p>
* <b>Note: The modelOutput is closed after reading or in case of an exception.</b>
* </p>
*/
public static void saveModel(Writer modelOutput, Model model) throws IOException {
int nr_feature = model.nr_feature;
int w_size = nr_feature;
if (model.bias >= 0) {
w_size++;
}
int nr_w = model.nr_class;
if (model.nr_class == 2 && model.solverType != SolverType.MCSVM_CS) {
nr_w = 1;
}
Formatter formatter = new Formatter(modelOutput, DEFAULT_LOCALE);
try {
printf(formatter, "solver_type %s\n", model.solverType.name());
printf(formatter, "nr_class %d\n", model.nr_class);
if (model.label != null) {
printf(formatter, "label");
for (int i = 0; i < model.nr_class; i++) {
printf(formatter, " %d", model.label[i]);
}
printf(formatter, "\n");
}
printf(formatter, "nr_feature %d\n", nr_feature);
printf(formatter, "bias %.16g\n", model.bias);
printf(formatter, "w\n");
for (int i = 0; i < w_size; i++) {
for (int j = 0; j < nr_w; j++) {
double value = model.w[i * nr_w + j];
/** this optimization is the reason for {@link Model#equals(double[], double[])} */
if (value == 0.0) {
printf(formatter, "%d ", 0);
} else {
printf(formatter, "%.16g ", value);
}
}
printf(formatter, "\n");
}
formatter.flush();
IOException ioException = formatter.ioException();
if (ioException != null) {
throw ioException;
}
} finally {
formatter.close();
}
}
private void printStatistics() {
for (int level = 0; level < maxLevel; level++) {
int bucketCountInLevel = 0;
SortedMap<Integer, Integer> levelMap = bucketSizesPerLevel
.get(level);
Iterator<Integer> bucketSizeIterator = levelMap.keySet().iterator();
LOG.debug("Statistics for level: " + level);
LOG.debug("----------------------------------------------");
LOG.debug("");
LOG.debug("Bucket Size | Count");
LOG.debug("------------------------");
int i = 0;
while (bucketSizeIterator.hasNext()) {
int bucketSize = bucketSizeIterator.next();
if (bucketSize != 0) {
int countForBucketSize = levelMap.get(bucketSize);
bucketCountInLevel += countForBucketSize;
Formatter formatter = new Formatter();
formatter.format(" %10d | %10d", bucketSize, countForBucketSize);
if (levelMap.size() < 20 || i < 3 || i >= (levelMap.size() - 3)) {
LOG.debug(formatter.out());
} else if (levelMap.size() / 2 == i) {
LOG.debug(" .. | ..");
LOG.debug(formatter.out());
LOG.debug(" .. | ..");
}
i++;
formatter.close();
}
}
LOG.debug("");
LOG.debug("Number of non-empty buckets in level: "
+ bucketCountInLevel);
LOG.debug("Number of empty buckets in level : "
+ levelMap.get(0));
LOG.debug("Number of different bucket sizes : "
+ (levelMap.size() - 1));
LOG.debug("");
LOG.debug("");
LOG.debug("");
}
}
/**
* Generates a property filter condition string for a <code>byte[]</code> value. Creates a formatted string to use
* in a filter expression that uses the specified operation to compare the property with the value, formatted as a
* binary value, as in the following example:
* <p>
* <code>String condition = generateFilterCondition("ByteArray", QueryComparisons.EQUAL, new byte[] {0x01, 0x0f});</code>
* <p>
* This statement sets <code>condition</code> to the following value:
* <p>
* <code>ByteArray eq X'010f'</code>
*
* @param propertyName
* A <code>String</code> which specifies the name of the property to compare.
* @param operation
* A <code>String</code> which specifies the comparison operator to use.
* @param value
* A <code>byte</code> array which specifies the value to compare with the property.
* @return
* A <code>String</code> which represents the formatted filter condition.
*/
public static String generateFilterCondition(String propertyName, String operation, final byte[] value) {
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb);
for (byte b : value) {
formatter.format("%02x", b);
}
formatter.flush();
formatter.close();
return generateFilterCondition(propertyName, operation, sb.toString(), EdmType.BINARY);
}