Java 使用\t排列文件输出

Java 使用\t排列文件输出,java,file-io,spacing,Java,File Io,Spacing,我正在尝试格式化一个文件输出,这样所有的东西都排列得很好,并且几乎可以正常工作。我使用\t尝试为输出提供统一的刚性外观。它就快到了,但对一个团队来说并不太有效(见下文),我想这是因为团队名称太短了,但我不确定有什么建议 我的代码: while ((str = in.readLine()) != null) { Team newTeam = new Team(str); teamArray[counter] = newTeam;

我正在尝试格式化一个文件输出,这样所有的东西都排列得很好,并且几乎可以正常工作。我使用\t尝试为输出提供统一的刚性外观。它就快到了,但对一个团队来说并不太有效(见下文),我想这是因为团队名称太短了,但我不确定有什么建议

我的代码:

while ((str = in.readLine()) != null) {
            Team newTeam = new Team(str);
            teamArray[counter] = newTeam;
            out.println(newTeam.getTeamName() + ": "+ "\t"  + newTeam.getBatAvgStr() + " " + newTeam.getSlugAvgStr());
我的输出:

2011年常规赛 尝试使用String.Format()

例如:

>     public static String padRight(String s, int n) {
>          return String.format("%1$-" + n + "s", s);  
>     }
>     
>     public static String padLeft(String s, int n) {
>         return String.format("%1$" + n + "s", s);  
>     }
>     
>     ...
>     
>     public static void main(String args[]) throws Exception {
>      System.out.println(padRight("Howto", 20) + "*");
>      System.out.println(padLeft("Howto", 20) + "*");
>     }

/*
  output :
     Howto               *
                    Howto*
*/

答案如下:

这是因为“Texas”的字母太少,无法将第一个制表符与其他制表符对齐。假设您使用的是
PrintWriter
,则可以使用而不是
println
,并使用格式说明符填充
字符串
标记:

out.printf("%14s:  %14s  %14s", 
             newTeam.getTeamName(), newTeam.getBatAvgStr(),  
                newTeam.getSlugAvgStr());

也许您可以使用smth,如:

while ((str = in.readLine()) != null) 
{
        Team newTeam = new Team(str);
        teamArray[counter] = newTeam;
        out.println(String.format("%1$-20s : %2$-5s %3$-5s",newTeam.getTeamName(), newTeam.getBatAvgStr(), newTeam.getSlugAvgStr()));

但是我没有测试它,所以我不确定…

这太棒了!!谢谢
while ((str = in.readLine()) != null) 
{
        Team newTeam = new Team(str);
        teamArray[counter] = newTeam;
        out.println(String.format("%1$-20s : %2$-5s %3$-5s",newTeam.getTeamName(), newTeam.getBatAvgStr(), newTeam.getSlugAvgStr()));