有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用java格式化字符串并写入文件

我有一些字符串需要格式化并写入文件

示例字符串

text1
text2
text3
text4
text5
text6
text7
text8
text9
text10
text11
text12
text13

前10行应该放在第一列,其余的行应该放在第二列。从第一列到第二列应该有30个空格

这就是我试过的

   File f = new File("sample.txt");
        FileWriter fw = new FileWriter(f);
        pw = new PrintWriter(fw);
        String text;

        for(int i=0; i<15; i++){
                text = "text" + i;

                if(i <= 10){
                    pw.format(text + "\n");
                } else{
                    pw.format("%30s",text + "\n");
                }    
            }
        }

我附上了预期输出的图像

enter image description here


共 (1) 个答案

  1. # 1 楼答案

    试试看

        for (int i = 1; i <= 10; i++) {
            String text1 = "text" + i;
            String text2 = i <= 3 ? "text" + (i + 10) : "";
            System.out.printf("%s%30s\n", text1, text2);
        }
    

    输出

    text1                        text11
    text2                        text12
    text3                        text13
    text4                              
    text5                              
    text6                              
    text7                              
    text8                              
    text9                              
    text10