Pregunta

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.

¿Fue útil?

Solución

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.

Otros consejos

I'm not sure you can do that, although I have not used Google Guava. Here is a suggestion, write the files to a CSV, a comma separated file. To do this, simply change your output to MyFile.csv then add a comma "," after every value you write. This file can be opened in any Spreadsheet program, with each value in its own cell, hence the solution will be neat.

If this doesn't work, ie, if it must be a txt file, here is a another idea. Loop thorough every single string you have to write, find the longest, and then adjust every other string you have to that length by adding white space to it.

I hope this helps!

Since you already have guava on the classpath.. I am going to show you what I came up with, but this is probably over-simplified and needs some more work to be done, even though not too much.

You need to always know the maximum size of the String in one row. I am calculating here only one actually:

    private static final class SortBylenght extends Ordering<String>{
        @Override
        public int compare(String left, String right) {
            return Ints.compare(left.length(), right.length());
        }
    }

Then calculate the max:

    ImmutableList<String> data = ImmutableList.of(firstName, school);
    SortBylenght sortBylenght = new SortBylenght();
    String maxString = sortBylenght.max(data);
    int maxSize = maxString.length();

Then print:

  bw.write(Strings.padEnd(firstName, maxSize, ' '));
  for(int i=0;i<20;++i) bw.write(' ');
  //You need to pad the end here of course again like in the first row; 
  bw.write(secondName);
  bw.newLine();
  bw.write(Strings.padEnd(school, maxSize, ' '));
  for(int i=0;i<20;++i) bw.write(' ');
  //You need to pad the end here of course again like in the first row; 
  bw.write(yob);

Use padEnd(), not padStart(). padStart() would be if you wanted to right-align your columns.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top