下面列出了java.text.MessageFormat#setFormat ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static void writeFormatToFile(final String name) {
try {
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream(name));
MessageFormat fmt = new MessageFormat("The disk \"{1}\" contains {0}.");
double[] filelimits = {0,1,2};
String[] filepart = {"no files","one file","{0,number} files"};
ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
fmt.setFormat(1,fileform); // NOT zero, see below
out.writeObject(fmt);
out.close();
} catch (Exception e) {
System.out.println(e);
}
}
private static void writeFormatToFile(final String name) {
try {
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream(name));
MessageFormat fmt = new MessageFormat("The disk \"{1}\" contains {0}.");
double[] filelimits = {0,1,2};
String[] filepart = {"no files","one file","{0,number} files"};
ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
fmt.setFormat(1,fileform); // NOT zero, see below
out.writeObject(fmt);
out.close();
} catch (Exception e) {
System.out.println(e);
}
}
private static void writeFormatToFile(final String name) {
try {
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream(name));
MessageFormat fmt = new MessageFormat("The disk \"{1}\" contains {0}.");
double[] filelimits = {0,1,2};
String[] filepart = {"no files","one file","{0,number} files"};
ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
fmt.setFormat(1,fileform); // NOT zero, see below
out.writeObject(fmt);
out.close();
} catch (Exception e) {
System.out.println(e);
}
}
private static void writeFormatToFile(final String name) {
try {
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream(name));
MessageFormat fmt = new MessageFormat("The disk \"{1}\" contains {0}.");
double[] filelimits = {0,1,2};
String[] filepart = {"no files","one file","{0,number} files"};
ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
fmt.setFormat(1,fileform); // NOT zero, see below
out.writeObject(fmt);
out.close();
} catch (Exception e) {
System.out.println(e);
}
}
public MCRCommand(Method cmd) {
className = cmd.getDeclaringClass().getName();
methodName = cmd.getName();
parameterTypes = cmd.getParameterTypes();
org.mycore.frontend.cli.annotation.MCRCommand cmdAnnotation = cmd
.getAnnotation(org.mycore.frontend.cli.annotation.MCRCommand.class);
help = cmdAnnotation.help();
messageFormat = new MessageFormat(cmdAnnotation.syntax(), Locale.ROOT);
setMethod(cmd);
for (int i = 0; i < parameterTypes.length; i++) {
Class<?> paramtype = parameterTypes[i];
if (ClassUtils.isAssignable(paramtype, Integer.class, true)
|| ClassUtils.isAssignable(paramtype, Long.class, true)) {
messageFormat.setFormat(i, NumberFormat.getIntegerInstance(Locale.ROOT));
} else if (!String.class.isAssignableFrom(paramtype)) {
unsupportedArgException(className + "." + methodName, paramtype.getName());
}
}
int pos = cmdAnnotation.syntax().indexOf("{");
suffix = pos == -1 ? cmdAnnotation.syntax() : cmdAnnotation.syntax().substring(0, pos);
}
private static void writeFormatToFile(final String name) {
try {
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream(name));
MessageFormat fmt = new MessageFormat("The disk \"{1}\" contains {0}.");
double[] filelimits = {0,1,2};
String[] filepart = {"no files","one file","{0,number} files"};
ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
fmt.setFormat(1,fileform); // NOT zero, see below
out.writeObject(fmt);
out.close();
} catch (Exception e) {
System.out.println(e);
}
}
protected String formatWithTimeZone(
String template,
Object[] arguments,
Locale locale,
TimeZone timezone)
{
MessageFormat mf = new MessageFormat(" ");
mf.setLocale(locale);
mf.applyPattern(template);
if (!timezone.equals(TimeZone.getDefault()))
{
Format[] formats = mf.getFormats();
for (int i = 0; i < formats.length; i++)
{
if (formats[i] instanceof DateFormat)
{
DateFormat temp = (DateFormat) formats[i];
temp.setTimeZone(timezone);
mf.setFormat(i,temp);
}
}
}
return mf.format(arguments);
}
protected String formatWithTimeZone(
String template,
Object[] arguments,
Locale locale,
TimeZone timezone)
{
MessageFormat mf = new MessageFormat(" ");
mf.setLocale(locale);
mf.applyPattern(template);
if (!timezone.equals(TimeZone.getDefault()))
{
Format[] formats = mf.getFormats();
for (int i = 0; i < formats.length; i++)
{
if (formats[i] instanceof DateFormat)
{
DateFormat temp = (DateFormat) formats[i];
temp.setTimeZone(timezone);
mf.setFormat(i,temp);
}
}
}
return mf.format(arguments);
}
public static void main(String[] args) {
int planet = 7;
String event = "a disturbance in the Force";
String messageFormatPattern = "At {1,time,long} on {1,date,full}, there was {2} on planet {0,number,integer}.";
MessageFormat messageFormat = new MessageFormat(messageFormatPattern);
String result = messageFormat.format(new Object[]{planet, new Date(), event});
System.out.println(result);
// 重置 MessageFormatPattern
// applyPattern
messageFormatPattern = "This is a text : {0}, {1}, {2}";
messageFormat.applyPattern(messageFormatPattern);
result = messageFormat.format(new Object[]{"Hello,World", "666"});
System.out.println(result);
// 重置 Locale
messageFormat.setLocale(Locale.ENGLISH);
messageFormatPattern = "At {1,time,long} on {1,date,full}, there was {2} on planet {0,number,integer}.";
messageFormat.applyPattern(messageFormatPattern);
result = messageFormat.format(new Object[]{planet, new Date(), event});
System.out.println(result);
// 重置 Format
// 根据参数索引来设置 Pattern
messageFormat.setFormat(1,new SimpleDateFormat("YYYY-MM-dd HH:mm:ss"));
result = messageFormat.format(new Object[]{planet, new Date(), event});
System.out.println(result);
}
/**
* Resolve an artifact and return its location in the local repository. Aether performs the normal
* Maven resolution process ensuring that the latest update is cached to the local repository.
* In addition, if the {@link MavenProperties#resolvePom} flag is <code>true</code>,
* the POM is also resolved and cached.
* @param resource the {@link MavenResource} representing the artifact
* @return a {@link FileSystemResource} representing the resolved artifact in the local repository
* @throws IllegalStateException if the artifact does not exist or the resolution fails
*/
Resource resolve(MavenResource resource) {
Assert.notNull(resource, "MavenResource must not be null");
validateCoordinates(resource);
RepositorySystemSession session = newRepositorySystemSession(this.repositorySystem,
this.properties.getLocalRepository());
ArtifactResult resolvedArtifact;
try {
List<ArtifactRequest> artifactRequests = new ArrayList<>(2);
if (properties.isResolvePom()) {
artifactRequests.add(new ArtifactRequest(toPomArtifact(resource),
this.remoteRepositories,
JavaScopes.RUNTIME));
}
artifactRequests.add(new ArtifactRequest(toJarArtifact(resource),
this.remoteRepositories,
JavaScopes.RUNTIME));
List<ArtifactResult> results = this.repositorySystem.resolveArtifacts(session, artifactRequests);
resolvedArtifact = results.get(results.size() - 1);
}
catch (ArtifactResolutionException e) {
ChoiceFormat pluralizer = new ChoiceFormat(
new double[] { 0d, 1d, ChoiceFormat.nextDouble(1d) },
new String[] { "repositories: ", "repository: ", "repositories: " });
MessageFormat messageFormat = new MessageFormat(
"Failed to resolve MavenResource: {0}. Configured remote {1}: {2}");
messageFormat.setFormat(1, pluralizer);
String repos = properties.getRemoteRepositories().isEmpty()
? "none"
: StringUtils.collectionToDelimitedString(properties.getRemoteRepositories().keySet(), ",", "[", "]");
throw new IllegalStateException(
messageFormat.format(new Object[] { resource, properties.getRemoteRepositories().size(), repos }),
e);
}
return toResource(resolvedArtifact);
}
@Override
public void setLinkDay(Date linkDay) {
MessageFormat todayFormat = new MessageFormat(AppBeans.get(Messages.class).getMessage("com.haulmont.cuba.desktop", "DatePicker.linkFormat"));
todayFormat.setFormat(0, new SimpleDateFormat(Datatypes.getFormatStrings(AppBeans.get(UserSessionSource.class).getLocale()).getDateFormat()));
setLinkFormat(todayFormat);
super.setLinkDay(linkDay);
}
public void test_equalsLjava_lang_Object() {
MessageFormat format1 = new MessageFormat("{0}");
MessageFormat format2 = new MessageFormat("{1}");
assertTrue("Should not be equal", !format1.equals(format2));
format2.applyPattern("{0}");
assertTrue("Should be equal", format1.equals(format2));
SimpleDateFormat date = (SimpleDateFormat) DateFormat.getTimeInstance();
format1.setFormat(0, DateFormat.getTimeInstance());
format2.setFormat(0, new SimpleDateFormat(date.toPattern()));
assertTrue("Should be equal2", format1.equals(format2));
}
/**
* Creates a new MCRCommand.
*
* @param format
* the command syntax, e.g. "save document {0} to directory {1}"
* @param methodSignature
* the method to invoke, e.g. "miless.commandline.DocumentCommands.saveDoc int String"
* @param helpText
* the helpt text for this command
*/
public MCRCommand(String format, String methodSignature, String helpText) {
StringTokenizer st = new StringTokenizer(methodSignature, " ");
String token = st.nextToken();
int point = token.lastIndexOf(".");
className = token.substring(0, point);
methodName = token.substring(point + 1);
int numParameters = st.countTokens();
parameterTypes = new Class<?>[numParameters];
messageFormat = new MessageFormat(format, Locale.ROOT);
for (int i = 0; i < numParameters; i++) {
token = st.nextToken();
Format f = null;
switch (token) {
case "int":
parameterTypes[i] = Integer.TYPE;
f = NumberFormat.getIntegerInstance(Locale.ROOT);
break;
case "long":
parameterTypes[i] = Long.TYPE;
f = NumberFormat.getIntegerInstance(Locale.ROOT);
break;
case "String":
parameterTypes[i] = String.class;
break;
default:
unsupportedArgException(methodSignature, token);
}
messageFormat.setFormat(i, f);
}
int pos = format.indexOf("{");
suffix = pos == -1 ? format : format.substring(0, pos);
if (helpText != null) {
help = helpText;
} else {
help = "No help text available for this command";
}
}