Printing with "\t" (tabs) does not result in aligned columns

Unknown user picture Unknown user · May 14, 2011 · Viewed 217.4k times · Source

I have a very weird problem. After writing this:

for (File f : currentFile.listFiles()) {            
    if  (f.isDirectory()){
        System.out.println(f.getName()+"\t"+"Dir\t"+Command.getpremission(f)+"\t"+f.getTotalSpace());
    }
    else{
        System.out.println(f.getName()+"\t"+"File\t"+Command.getpremission(f)+"\t"+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?

Answer

Matthias Braun picture Matthias Braun · Jan 1, 2014

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.