为了账号安全,请及时绑定邮箱和手机立即绑定

如何打印到同一行?

如何打印到同一行?

呼啦一阵风 2019-10-30 10:36:11
我想像这样打印进度条:[#                    ] 1%[##                   ] 10%[##########           ] 50%但是这些都应该打印到终端的同一行,而不是新行。我的意思是,每个新行都应替换上一行,而不是使用print()代替println()。如何用Java做到这一点?
查看完整描述

3 回答

?
Cats萌萌

TA贡献1805条经验 获得超9个赞

格式化字符串,如下所示:


[#                    ] 1%\r

注意\r字符。就是所谓的回车,它将把光标移回该行的开头。


最后,请确保您使用


System.out.print()

并不是


System.out.println()


查看完整回答
反对 回复 2019-10-30
?
呼唤远方

TA贡献1856条经验 获得超11个赞

在Linux中,控制终端有不同的转义序列。例如,有一个特殊的转义序列可擦除整行:\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)");

有用于光标导航,清除屏幕等的代码。


我认为有些图书馆对此有帮助(ncurses?)。


查看完整回答
反对 回复 2019-10-30
?
慕森王

TA贡献1777条经验 获得超3个赞

首先,我很抱歉提出这个问题,但我认为它可以使用另一个答案。


德里克·舒尔茨(Derek Schultz)是对的。'\ b'字符将打印光标向后移动一个字符,使您可以覆盖在那里打印的字符(除非您在顶部打印新信息,否则它不会删除整行甚至是那里的字符)。以下是使用Java的进度条的示例,尽管它不遵循您的格式,但显示了如何解决覆盖字符的核心问题(仅在32位计算机上的Ubuntu 12.04中使用Oracle Java 7进行了测试,但它应可在所有Java系统上使用):


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();

    }

}


查看完整回答
反对 回复 2019-10-30
  • 3 回答
  • 0 关注
  • 813 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信