How can I (in java) generate file names from a mask string?

I want to generate file names from a mask in Java.

Something like “Data-12-08-29-xxx.xml” from a mask like “Data - $ {YY} - $ {MM} - $ {DD} - $ {var1} .xml '. I don't want to generate random file names; instead, the file names will be constructed according to the template provided at runtime.

I can imagine what I need to create a good universal class that will handle this for all cases, but I do not want to reinvent the wheel if something exists there that I can reuse and possibly extend.

Any suggestions?

+7
source share
5 answers

You can use a small library called AlephFormatter , which allows you to have "named" parameters.

For example:

String result = template("#{errNo} -> #{c.simpleName} -> #{c.package.name}") .arg("errNo", 101) .arg("c", String.class) .fmt(); System.out.println(result); 

Output:

 Error number: 101 -> String -> java.lang 
0
source

the Formatter class (functionality beyond String.format() ) has a very powerful formatting syntax (much more powerful than MessageFormat). It can handle variable substitution as well as date formatting.

+3
source
  Format f=new SimpleDateFormat("dd-MM-yyyy-HH.mm.ss"); String fileName="Data-"+f.format(new Date() /*or a Date object which you saved previously*/).toString()+".xml"; 

This will give you something like Data-12-12-2012-14.55.32.xml

+2
source
 MessageFormat messageFormat = new MessageFormat("Data-{0,number,#}-{1}-{2}-{3,number,#}.xml"); Calendar cal = Calendar.getInstance(); int variable = 555; Integer[] args = {cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DAY_OF_MONTH), variable}; String result = messageFormat.format(args); System.out.println(result); 

OUTPUT:

Data-2012-8-29-555.xml

+1
source

The problem with String.format () is that you will be forced to use the indices of your variables in the format string, and a template similar to %1$ty-%1$tm-%1$td-%2$03d may be problematic for the user:

 Calendar time = Calendar.getInstance(); int number = 7; String msg = String.format("Data-%1$ty-%1$tm-%1$td-%2$03d.xml", time, number); 

In one of my projects, I decided to use Apache Velocity (here is an example: http://www.javaworld.com/javaworld/jw-12-2001/jw-1228-velocity.html ). This is a fairly powerful tool for this kind of tasks, but it makes it possible to use meaningful variable names in your format Date-${year}-${month}-${day}-${number}.xml . First, you need to add the appropriate variables to the speed context:

 VelocityContext context = new VelocityContext(); context.put("number", "007"); context.put("year", ...); 

but then it will be much easier for the user to specify a format string.

0
source

All Articles