[英]Using Google Guava to format Strings
我正在使用Google guava格式化Strings并使用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);
}
}
}
我的输出是
我需要输出
我从数据库接收字符串和数据库和硬编码上面只是一个例子,我需要编写字符串,这样第一个字符串的长度不会影响第二个字符串的Beginging Position。 我需要在Column Manner中使用Google Guava在同一位置编写它们。 我也会欣赏一些例子。
String.format
您可以简单地使用String.format()而不是Guava 。 它遵循此处描述的C printf语法。 我认为它符合您的需求。
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);
输出:
aaabb, abc,hello
如您所见,长字符串被剪切并且短字符串被填充。
虽然我还没有使用Google Guava,但我不确定你能做到这一点。 这是一个建议,将文件写入CSV,逗号分隔文件。 要执行此操作,只需将输出更改为MyFile.csv,然后在您编写的每个值后添加逗号“,”。 此文件可以在任何电子表格程序中打开,每个值都在其自己的单元格中,因此解决方案将是整洁的。
如果这不起作用,即,如果它必须是txt文件,这是另一个想法。 循环遍历您必须编写的每个字符串,找到最长的字符串,然后通过向其添加空格来调整您拥有的所有其他字符串。
我希望这有帮助!
因为你已经在类路径上有guava了。我将向你展示我想出的东西,但这可能过度简化了,需要做更多的工作,即使不是太多。
您需要始终知道一行中String的最大大小。 我这里只计算一个:
private static final class SortBylenght extends Ordering<String>{
@Override
public int compare(String left, String right) {
return Ints.compare(left.length(), right.length());
}
}
然后计算最大值:
ImmutableList<String> data = ImmutableList.of(firstName, school);
SortBylenght sortBylenght = new SortBylenght();
String maxString = sortBylenght.max(data);
int maxSize = maxString.length();
然后打印:
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);
使用padEnd()
,而不是padStart()
。 padStart()
将是你想要对齐你的列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.