3 回答

TA貢獻1797條經(jīng)驗 獲得超4個贊
格式化字符串,如下所示:
[# ] 1%\r
注意\r字符。就是所謂的回車,它將把光標移回該行的開頭。
最后,請確保您使用
System.out.print()
并不是
System.out.println()

TA貢獻1804條經(jīng)驗 獲得超2個贊
在Linux中,控制終端有不同的轉(zhuǎn)義序列。例如,有一個特殊的轉(zhuǎn)義序列可擦除整行:\33[2K并將光標移至前一行:\33[1A。因此,您所需要的只是每次刷新行時都要打印一次。這是打印的代碼Line 1 (second variant):
System.out.println("Line 1 (first variant)");
System.out.print("\33[1A\33[2K");
System.out.println("Line 1 (second variant)");
有用于光標導(dǎo)航,清除屏幕等的代碼。
我認為有些圖書館對此有幫助(ncurses?)。

TA貢獻2021條經(jīng)驗 獲得超8個贊
首先,我很抱歉提出這個問題,但我認為它可以使用另一個答案。
德里克·舒爾茨(Derek Schultz)是對的。'\ b'字符將打印光標向后移動一個字符,使您可以覆蓋在那里打印的字符(除非您在頂部打印新信息,否則它不會刪除整行甚至是那里的字符)。以下是使用Java的進度條的示例,盡管它不遵循您的格式,但顯示了如何解決覆蓋字符的核心問題(僅在32位計算機上的Ubuntu 12.04中使用Oracle Java 7進行了測試,但它應(yīng)可在所有Java系統(tǒng)上使用):
public class BackSpaceCharacterTest
{
// the exception comes from the use of accessing the main thread
public static void main(String[] args) throws InterruptedException
{
/*
Notice the user of print as opposed to println:
the '\b' char cannot go over the new line char.
*/
System.out.print("Start[ ]");
System.out.flush(); // the flush method prints it to the screen
// 11 '\b' chars: 1 for the ']', the rest are for the spaces
System.out.print("\b\b\b\b\b\b\b\b\b\b\b");
System.out.flush();
Thread.sleep(500); // just to make it easy to see the changes
for(int i = 0; i < 10; i++)
{
System.out.print("."); //overwrites a space
System.out.flush();
Thread.sleep(100);
}
System.out.print("] Done\n"); //overwrites the ']' + adds chars
System.out.flush();
}
}
添加回答
舉報