[使用String.format java以正确的方式对齐所有字符串

问题描述 投票:0回答:1

我通过在StringBuilder中附加所有字符串,然后将其转储到文件中来创建文件。但是当我检查文件时(很明显),我在每一行中的所有字符串都没有正确对齐。

下面是通过传递所有必要内容的上层调用的代码。

  private static StringBuilder appendStrings(String pro, List<ProcConfig> list,
      StringBuilder sb) {
    for (ProcConfig pc : list) {
      sb.append(pro).append(" ").append(pc.getNo()).append(" ").append(pc.getId())
          .append(" ").append(pc.getAddress()).append(" ").append(pc.getPort()).append(" ")
          .append(pc.getNumPorts()).append(" ").append(pc.getName())
          .append(System.getProperty("line.separator"));
    }
    sb.append(System.getProperty("line.separator"));
    return sb;
  }

这是上面代码中的样例行。每条新行之后都有一个新集,因此我想在每组新行之前将每组中的所有行正确对齐。

config 51 106 10.178.151.25 8095 5 tyt_87612nsas_woqa_7y2_0
config 51 104 10.124.192.124 8080 5 tyt_abc_pz1_rn03c-7vb_01

if_hello_abc_tree tyt.* then process_is_not_necessary 32 80 10.86.25.29 9091 5 tyt_goldenuserappslc22
if_hello_abc_tree tyt.* then process_is_not_necessary 51 50 10.174.192.209 9091 5 tyt_goldenuserapprno01

if_hello_abc_tree tyt.* then config 4 140 10.914.198.26 10001 1 silos_lvskafka-1702600
if_hello_abc_tree tyt.* then config 4 184 10.444.289.138 10001 1 silos_lvskafka-1887568

我有什么方法可以正确对齐以上每一行?所以输出应该是这样的:

config 51 106 10.178.151.25  8095 5 tyt_87612nsas_woqa_7y2_0
config 51 104 10.124.192.124 8080 5 tyt_abc_pz1_rn03c-7vb_01

if_hello_abc_tree tyt.* then process_is_not_necessary 32 80 10.86.25.29    9091 5 tyt_goldenuserappslc22
if_hello_abc_tree tyt.* then process_is_not_necessary 51 50 10.174.192.209 9091 5 tyt_goldenuserapprno01

if_hello_abc_tree tyt.* then config 4 140 10.914.198.26  10001 1 silos_lvskafka-1702600
if_hello_abc_tree tyt.* then config 4 184 10.444.289.138 10001 1 silos_lvskafka-1887568

更新:

下面是现在如何生成它。正如您在IP地址上看到的那样,如果将这两行进行比较,它会稍微偏离。

config 51 106   97.143.765.65 8095 5 abc_tyewaz1_rna03c-7nhl_02 
config 51 104  97.143.162.184 8080 5 abc_tyewaz1_rna03c-7vjb_01 

相反,我们可以生成以下内容吗?基本上使各列笔直。这可能吗?

config 51 106  97.143.765.65  8095 5 abc_tyewaz1_rna03c-7nhl_02 
config 51 104  97.143.162.184 8080 5 abc_tyewaz1_rna03c-7vjb_01 

我通过在StringBuilder中附加所有字符串,然后将其转储到文件中来创建文件。但是,当我检查文件(很明显)时,我在每一行中的所有字符串都没有正确对齐。....

java string-formatting stringbuilder
1个回答
1
投票

首先:我不是Java开发人员,但是我对此有所了解。我知道这不是解决问题的最佳方法,但您会明白这一点。

© www.soinside.com 2019 - 2024. All rights reserved.