使用“ "打印(标签)不会导致对齐的列

2022-01-09 00:00:00 tabs java text-formatting

我有一个非常奇怪的问题.写完之后:

for (File f : currentFile.listFiles()) {if (f.isDirectory()){System.out.println(f.getName()+"	"+"Dir	"+Command.getpremission(f)+"	"+f.getTotalSpace());}别的{System.out.println(f.getName()+"	"+"文件	"+Command.getpremission(f)+"	"+f.getTotalSpace());}

我看到这个打印出来了:

see.txt 文件 rw 267642728448see1.txt 文件 rw 267642728456see2.txt 文件 rw 267642728448

为什么标签有问题?

解决方案

基于这个问题,我使用以下代码来缩进我的消息:

String prefix1 = "短文本:";字符串前缀 2 = "looooooooooooooong 文本:";String msg = "缩进";/** 第二个字符串在 40 个字符之后开始.破折号表示* 第一个字符串是左对齐的.*/字符串格式 = "%-40s%s%n";System.out.printf(格式,前缀1,味精);System.out.printf(格式,前缀2,味精);

这是输出:

<上一页>短文本:缩进looooooooooooooong 文本:缩进

这在 man 3 printf 中的标志字符"部分中有记录.

I have a very weird problem. After writing this:

for (File f : currentFile.listFiles()) {            
    if  (f.isDirectory()){
        System.out.println(f.getName()+"	"+"Dir	"+Command.getpremission(f)+"	"+f.getTotalSpace());
    }
    else{
        System.out.println(f.getName()+"	"+"File	"+Command.getpremission(f)+"	"+f.getTotalSpace());
    }

I see this printed:

see.txt File    rw  267642728448
see1.txt    File    rw  267642728456
see2.txt    File    rw  267642728448

Why is there a problem with the tabs?

解决方案

Building on this question, I use the following code to indent my messages:

String prefix1 = "short text:";
String prefix2 = "looooooooooooooong text:";
String msg = "indented";
/*
* The second string begins after 40 characters. The dash means that the
* first string is left-justified.
*/
String format = "%-40s%s%n";
System.out.printf(format, prefix1, msg);
System.out.printf(format, prefix2, msg);

This is the output:

short text:                             indented
looooooooooooooong text:                indented

This is documented in section "Flag characters" in man 3 printf.

相关文章