3 回答

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

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超2個(gè)贊
在Linux中,控制終端有不同的轉(zhuǎn)義序列。例如,有一個(gè)特殊的轉(zhuǎn)義序列可擦除整行:\33[2K并將光標(biāo)移至前一行:\33[1A。因此,您所需要的只是每次刷新行時(shí)都要打印一次。這是打印的代碼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)");
有用于光標(biāo)導(dǎo)航,清除屏幕等的代碼。
我認(rèn)為有些圖書(shū)館對(duì)此有幫助(ncurses?)。

TA貢獻(xiàn)2021條經(jīng)驗(yàn) 獲得超8個(gè)贊
首先,我很抱歉提出這個(gè)問(wèn)題,但我認(rèn)為它可以使用另一個(gè)答案。
德里克·舒爾茨(Derek Schultz)是對(duì)的。'\ b'字符將打印光標(biāo)向后移動(dòng)一個(gè)字符,使您可以覆蓋在那里打印的字符(除非您在頂部打印新信息,否則它不會(huì)刪除整行甚至是那里的字符)。以下是使用Java的進(jìn)度條的示例,盡管它不遵循您的格式,但顯示了如何解決覆蓋字符的核心問(wèn)題(僅在32位計(jì)算機(jī)上的Ubuntu 12.04中使用Oracle Java 7進(jìn)行了測(cè)試,但它應(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();
}
}
添加回答
舉報(bào)