0

So basically I have a list of java objects that need to be written into a text file with a specific format.

eg.

class car
{
    String license;
    String color;
    String model;
    String numOfSeats;
}

and this has to be written into a text file where the format of each line is

license--color-----model-------numOfSeats------

The license must occupy 10 bytes, even if the length of the actual string is less.

The color must occupy 10 bytes, and the model must occupy 12 bytes etc.

So I want to create a template in such a way that I can just plug in the variables, and they occupy the required number of bytes (i.e. padded with spaces if shorter, truncated if longer)

So in the future, if the template changes, I don't need to make any code changes. I would just need to change the template.

I have been exploring JEXL but I am not sure how to achieve this with it.

ManoDestra
  • 6,325
  • 6
  • 26
  • 50
Fazil Hussain
  • 425
  • 3
  • 16
  • 1
    Have you looked at the standard Java printf() method (see [here](https://docs.oracle.com/javase/tutorial/essential/io/formatting.html))? If so, what is that missing? – Scott Kurz Jun 20 '16 at 16:22
  • Perhaps something along these lines: http://stackoverflow.com/questions/15635273/can-we-use-string-format-to-pad-prefix-with-a-character-with-desired-length? – ManoDestra Jul 18 '16 at 14:27

1 Answers1

1

I was able to achieve this using JEXL

expression = ${utilClass.rpad(car.getLicense(), 10)}

and

JexlEngine jexl = new JexlBuilder().create(); JxltEngine jxlt = jexl.createJxltEngine(); JxltEngine.Expression expr = jxlt.createExpression(expression); JexlContext context = new MapContext(); context.set("utilClass", new UtilClass());context.set("car", new Car())

expr.prepare(context); String s= expr.evaluate(context).toString();

I can get the expression from a file and thus if the layout changes, i just change the file and i don't need to touch the code.

Fazil Hussain
  • 425
  • 3
  • 16