java - Using Google Guava to format Strings -
i using google guava format strings , write them 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 
i need output

i receiving strings database , database , hardcoding above example, need write strings such length of first string doe not affect beginging position of second string. need write them in column manner beginging @ same position using google guava. appreciate examples also.
string.format
you can use string.format() instead of guava. follows c printf syntax described here. think meets 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 can see, long string cut , short string padded.
Comments
Post a Comment