Java字符串操作 – 添加空格或子字符串

我正在解构一个Java对象,从getter中获取所有必需的String值,并将所有这些值连接成每个对象一个String。 我然后我想存储每个字符串是一个

ArrayList 

我将每个对象的字符串连接成一个字符串,这样我就可以在pdf文档(pdfbox)中将其打印出来用于报告…我希望将每一行的格式设置为相同,就像在表格中一样。 例如,无论String1是3个字符还是103个字符长,它总是会填充25个字符的空间 – 要么使用较小的子字符串,要么使用空格进行缓冲,以根据需要进行调整。

我的问题是如何有效地做到这一点? 对于这个例子,假设我要求每个条目长度为25个字符。 因此,对于我在下面添加的每个值,我如何强制所有条目都是25个字符长?

  String SPACE=" "; for(People peeps: list){ builder = new StringBuilder(); name =(peeps.getName()); // if(name.length()>25){name=name.substring(0,25);} builder.append(name) .append(SPACE) .append(peeps.getCode()) .append(SPACE) .append(peeps.getReference()) .append(SPACE) .append(peeps.getDate()) .append(SPACE) .append(peeps.getStatus()) .append(SPACE) .append(peeps.getValue()); reportList.add(builder.toString()); } 

例如

使用Formatter类。

 StringBuilder sb = new StringBuilder(); Formatter formatter = new Formatter(sb); sb.append("|"); formatter.format("%-25.25s", "This is some text with more than 25 characters."); sb.append("|"); formatter.format("%-25.25s", "Some text with less."); sb.append("|"); formatter.format("%-25.25s", "Some other text."); sb.append("|"); System.out.println(formatter.toString()); 

输出:

 |This is some text with mo|Some text with less. |Some other text. | 

Apache Commons提供易于使用的API来与字符串一起使用:

 name = StringUtils.substring(name, 0, 25); name = StringUtils.leftPad(name, 25, ' ');