Java 如何在固定长度的字符串或字符缓冲区中的特定位置写入

Java 如何在固定长度的字符串或字符缓冲区中的特定位置写入,java,Java,我需要创建固定长度的记录,这些记录主要由空间组成,但在某些已知位置上却很少填充。本质上,我需要生成的是一种遗留文件格式,其中记录由大量固定长度字段组成。我只需要填充这些字段中的一小部分,所以我想先创建一个充满空格的空缓冲区,然后在特定位置写入特定长度的格式化字段 StringBuilder b = new StringBuilder();// Or use StringBufer if you need synchronization b.append("----------"); //use

我需要创建固定长度的记录,这些记录主要由空间组成,但在某些已知位置上却很少填充。本质上,我需要生成的是一种遗留文件格式,其中记录由大量固定长度字段组成。我只需要填充这些字段中的一小部分,所以我想先创建一个充满空格的空缓冲区,然后在特定位置写入特定长度的格式化字段

StringBuilder b = new StringBuilder();// Or use StringBufer if you need synchronization
b.append("----------"); //use dash instead of space for visibility
int pos = 4; 

String replacement = "foo";
b.replace(pos, pos + replacement.length(), replacement); //Attention: if the length of the replacement is greater than the length of the original content, the exceeding chars will be appended
System.out.println(b); //----foo---

考虑将StringUtils用于leftPad、rightPad、center和repeat


当您自己创建结果时,这会有所帮助,因此您实际上不需要处理位置和子字符串…

我不会首先创建一个长度为记录总长度的空格字符串。我只需要使用
StringBuilder
类并根据需要附加字段(需要时会自动增长)。在将字段添加到记录时,我会在每个字段中添加空格

public class FixedWidthBuilder {
  private StringBuilder record = new StringBuilder();

  public void append(int len, String value){
    if (len < value.length()){
      value = value.substring(0, len);
    } else if (len > value.length()){
      StringBuilder sb = new StringBuilder(value);
      for (int i = value.length(); i < len; i++){
        sb.append(' ');
      }
      value = sb.toString();
    }
    record.append(value);
  }

  @Override
  public String toString(){
    return record.toString();
  }
}
公共类FixedWidthBuilder{
私有StringBuilder记录=新StringBuilder();
public void append(int len,字符串值){
if(lenvalue.length()){
StringBuilder sb=新StringBuilder(值);
for(int i=value.length();i
您可能希望实现一个表示固定长度记录的类,该类了解记录中的每个字段。默认为所有空格,并为您关心的字段提供setter


在内部,实现取决于您。也许Thomas和user1001027的答案的组合似乎合理。

这对于格式化每个字段很有用,但由于记录的填充量很少,我不想为记录中的100个左右的字段中的每个字段生成一个空白字段,或者每次更新一个代码时,都必须更新代码以在使用的字段之间生成空白字符串。我认为简单性比效率更重要,所以我选择了Thomas的方法。感谢这一点-我快速查看了StringBuilder文档,但错过了替换方法。我添加了一个字符串长度检查,以确保不会意外扩展缓冲区:if(string.length()>length)抛出新的IllegalArgumentException(“输入字符串的长度>字段长度”);