Sunday, May 3, 2009

Seeking in PrintStream

I played with maven today. I found the following output message when maven is downloading something. The xxx changes to indicate the download progress.

xxx/yyyK

I am curious about how this is done. As far as I know, System.out is PrintStream. In PrintStream, there is no method to seek. I searched for the answer on the web. Unfortunately, I can't find the answer. I downloaded the maven source code. After some browsing, I found that printing \r will position the following printings at the beginning of a line. The following Java code shows how it is done.

import java.io.PrintStream;

public class Print {

public static void main(String[] args) {
PrintStream ps = System.out;
ps.print("100");
sleep2s();
ps.print("\r200");
sleep2s();
ps.print("\r300");
}

private static void sleep2s() {
try {
Thread.sleep(2 * 2000);
} catch (InterruptedException ie) {
throw new RuntimeException(ie);
}
}
}

I think that Javadoc should have documented this kind of usage, which can save developers a lot of time to scratch their heads.

No comments: