简体   繁体   中英

Writing strings to a fixed format file in java

I have several java objects with four string properties as below:

For eg 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 those 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM