Search code examples
javastringguavapad

Using Google Guava to format Strings


I am using Google guava to format Strings and write them to a text file using BufferedWriter

import com.google.common.base.Strings;
import java.io.*;

public class Test {

    public static void main(String[] args) {
        File f = new File("MyFile.txt");
        String firstName = "STANLEY";
        String secondName = "GATUNGO";
        String thirdname = "MUNGAI";
        String location = "NAIROBI";
        String school = "STAREHE BOYS CENTRE";
        String yob= "1970";
        String marital = "MARIED";
        String texture = "LIGHT";

        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(f));
            if (!f.exists()) {
                f.createNewFile();
            }
           bw.write(Strings.padStart(firstName, 0, ' '));
           bw.write(Strings.padStart(secondName, 20, ' '));
           bw.write(Strings.padStart(thirdname, 20, ' '));
           bw.write(Strings.padStart(location, 20, ' '));
           bw.newLine();
           bw.write(Strings.padStart(school, 0, ' '));
           bw.write(Strings.padStart(yob, 20, ' '));
           bw.write(Strings.padStart(marital, 20, ' '));
           bw.write(Strings.padStart(texture, 20, ' '));


            bw.close();
        } catch (Exception asd) {
            System.out.println(asd);
        }
    }
}

My Output is My output

I need the output to be

Desired Output

I am receiving the Strings from the database and the Database And the Hardcoding Above is Just an example, I need to write the Strings Such that the Length of the First String doe not affect the Beginging Position of the second String. I need to write them in Column Manner all beginging at the same Position using Google Guava. I will Appreciate examples also.


Solution

  • String.format

    You can simply use String.format() instead of Guava. It follows the C printf syntax described here. I think that it meets your needs.

    String aVeryLongString="aaabbbcccdddeeefffggghh";
    String aShortString="abc";
    String anotherString="helloWorld";
    
    String formattedString=String.format("%5.5s,%5.5s,%5.5s",aVeryLongString,aShortString,anotherString);
    
    System.out.println(formattedString);
    

    Output :

    aaabb,  abc,hello
    

    As you can see, the long String was cut and the short String was padded.