格式化具有固定宽度列的文本表



我有一个文件,里面有一些商店的信息,我想把它放在另一个文件中排序,比如表格(在Excel中)。

文件:

001     Tablets                        5      3
002     pens                           4      1
005     Computeres                     3      0
003     Bages                          2      1
004     USB                            4      0

我写这个代码:

import java.util.*;
import java.io.*;
public class Sort {
public static void main(String [] args) throws IOException {
    FileInputStream fileinput = new FileInputStream("input.txt");
    FileOutputStream fileoutput = new FileOutputStream("output.txt");
    Scanner infile = new Scanner(fileinput);
    PrintWriter pw = new PrintWriter(fileoutput);
    int id, quantity, soldQuantity;
    String title;
    pw.println("IDtTitletttQuantitytSoldQuantity");
    pw.println("");
    while(infile.hasNext()){
        id = infile.nextInt();
        title = infile.next();
        quantity = infile.nextInt();
        soldQuantity = infile.nextInt();
        pw.printf("%6dt%stt%dt%d%n", id , title, quantity, soldQuantity);
    }
    infile.close();
    pw.close();
}
}

我希望它看起来像这样:

Code(ID)    Name            Quantity    SoldQuantity
     001    Tablets                5               3
     002    pens                   4               1
     005    Computeres             3               0
     003    Bages                  2               1
     004    USB                    4               0

我的问题是数量和销售量的多少,不太合适。看起来像这样:

Code(ID)    Name            Quantity    SoldQuantity
     001    Tablets             5               3
     002    pens             4               1
     005    Computers             3               0
     003    Bags             2               1
     004    USB             4               0

当名称大小不同时就会出现问题。如果有一个名称大于"计算机",我该如何处理?

感谢

不要使用t作为间距,也要为字符串使用宽度修饰符:

pw.printf("%6dt%30s%dt%d%n", id, title, quantity, soldQuantity);

如果你真的想确保无论最长的title有多长,所有东西都排成一行,你可以找到最长的长度,加一个,然后用它把格式字符串粘贴在一起。

参见文档中的文档

样品:

Formatter formatter = new Formatter();
System.out.println(formatter.format("%10s %10s %10s", "Title1", "Title2", "Title3"));
for (int i = 0; i < 10; i++) {
        String row = "info" + i;
        System.out.println(formatter.format("%10s %10s %10s", row, row, row));
}

创建一个方法,根据Name列中项目的长度返回空格。

public String getSpaces(int len){
   int num = 23-len;
   char[] chars = new char[num];
   Arrays.fill(chars, ' ');
   return new String(chars);
}

现在这样做可以在标题后获得空格:

getSpaces(title.length);

希望这能帮助

uniVocity解析器有一个固定宽度的解析器/编写器,您应该使用它,而不是尝试编写自己的解析器/写入器。

您甚至可以使用带有注释的javabean。这里有一个例子:

class TestBean {
// if the value parsed in the quantity column is "?" or "-", it will be replaced by null.
@NullString(nulls = { "?", "-" })
// if a value resolves to null, it will be converted to the String "0".
@Parsed(defaultNullRead = "0")
private Integer quantity;   // The attribute type defines which conversion will be executed when processing the value.
// In this case, IntegerConversion will be used.
// The attribute name will be matched against the column header in the file automatically.
@Trim
@LowerCase
// the value for the comments attribute is in the column at index 4 (0 is the first column, so this means fifth column in the file)
@Parsed(index = 4)
private String comments;
// you can also explicitly give the name of a column in the file.
@Parsed(field = "amount")
private BigDecimal amount;
@Trim
@LowerCase
// values "no", "n" and "null" will be converted to false; values "yes" and "y" will be converted to true
@BooleanString(falseStrings = { "no", "n", "null" }, trueStrings = { "yes", "y" })
@Parsed
private Boolean pending;

让我们用TestBean编写一个固定宽度的文件:

FixedWidthFieldLengths lengths = new FixedWidthFieldLengths(10, 10, 35, 10, 40);
FixedWidthWriterSettings settings = new FixedWidthWriterSettings(lengths);
// Any null values will be written as ?
settings.setNullValue("?");
// Creates a BeanWriterProcessor that handles annotated fields in the TestBean class.
settings.setRowWriterProcessor(new BeanWriterProcessor<TestBean>(TestBean.class));
// Sets the file headers so the writer knows the correct order when writing values taken from a TestBean instance
settings.setHeaders("amount", "pending", "date", "quantity", "comments");
// Creates a writer with the above settings;
FixedWidthWriter writer = new FixedWidthWriter(outputWriter, settings);
// Writes the headers specified in the settings
writer.writeHeaders();
// writes a fixed width row with empty values (as nothing was set in the TestBean instance).
writer.processRecord(new TestBean());
TestBean bean = new TestBean();
bean.setAmount(new BigDecimal("500.33"));
bean.setComments("Blah,blah");
bean.setPending(false);
bean.setQuantity(100);
// writes a Fixed Width row with the values set in "bean". Notice that there's no annotated
// attribute for the "date" column, so it will just be null (an then converted to ?, as we have settings.setNullValue("?");)
writer.processRecord(bean);
// you can still write rows passing in its values directly.
writer.writeRow(BigDecimal.ONE, true, "1990-01-10", 3, null);

输出:

amount    pending   date                               quantity  comments
?         ?         ?                                  ?         ?
500.33    no        ?                                  100       blah,blah
1         true      1990-01-10                         3         ?

披露:我是这个图书馆的作者。它是开源和免费的(Apache V2.0许可证)。

相关内容

  • 没有找到相关文章

最新更新