繁体   English   中英

String.format()语句,用于分隔每行仅大括号

[英]String.format() statement for spacing each line only spaces braces

我试图利用String.format()方法在一个infile的每一行之前添加可变数量的空格,以产生一个新的outfile infile是一个.java文件,除了换行符外,所有空格都已删除,并且每个大括号都有其自己的行。

这是我的代码,我测试在每行之前添加3个空格。 请注意, Scanner参数来自main ,它接收infile

void printToOutFile(Scanner s, File o) throws IOException {
    FileWriter stream = new FileWriter(o);
    BufferedWriter out = new BufferedWriter(stream);
    int numOfSpaces = 3;

    while(s.hasNext()) {
        line = s.nextLine();
        String l = String.format("%1$" + numOfSpaces + "s", line);
        out.write(l + "\n");
    }
    out.close()
}

这里的String.format()似乎仅在任何大括号之前添加空格,而没有在文本行中添加空格。 我不知道为什么会那样做。

您在格式字符串中指定了宽度,但是我并不是那样做正是您想要的。 Formatter文档中:

可选宽度是一个非负十进制整数,指示要写入输出的最小字符数。

尝试这个:

String l = String.format("%1$" + (numOfSpaces + line.length()) + "s", line);

你有没有尝试过

format("%*s", numSpaces, line);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM