Writing strings to a fixed format file in java
I have several java objects with four string properties as below:
For e.g. say object1 is having values as
String one = "abcd"; //length 4
String two = "efghij"; //length 6
String three = "klmnop"; //length 6
String four = "qrs"; //length 3
I want to output above data in to a fixed format file.
The format would be: one is 10 characters, two is 8 characters, three is 9 characters, four is 10 characters.
So above example will be as: 6spaces+abcd+2spaces+efghij+3spaces+klmnop+6spaces+qrs
Thus what I want to achieve is convert each strings to the appropriate length as required by the file and then push thos开发者_Go百科e to the file.
How to achieve this most efficiently ??
The simplest way is propably to use String.format()
.
String formatted = String.format("%10s%8s%9s%10s", one, two, three, four);
The description of the format syntax can be found here.
If you have a particular prefix (or postfix) in mind, you could:
Create an array of strings with prefixes (or siffixes) with the length corresponding to the length of missing symbols, like:
String[] prefixes = {"", "#", "##", ...};
int desiredLength = 10;
String four = "abc";
four = prefixes[desiredLength - four.length] + four;
精彩评论