How do I perform “less” paging from a Java console application?

I need to execute the less command from my java console application, using paging However, I found that the only way to execute external commands is runtime getRuntime(). Exec (), which requires me to write / read I / O through the stream So commands like cat (and actually like cat), but I need pagination

In C, I use system () In ruby, kernel Exec finished the work

Is there any way to do this in Java?

Solution

Use runtime When exec () executes an external process, its standard input and output streams are not connected to the terminal running the Java program You can use shell redirection to connect to it, but first you need to know the terminal to use There is no way to find terminals using standard APIs, but you may find an open source library

In order to see that it can be completed, this program is rarely opened:

public class Test {
    public static void main(String[] args) throws Exception {
        Process p = Runtime.getRuntime().exec(
                new String[] {"sh","-c","less Test.java < "+args[0] + " > "+args[0]});
        System.out.println("=> "+p.waitFor());
    }
}

To run it, you should use java test $(TTY) The TTY program prints the name of the terminal connected to its standard input

I'm not sure about the portability of this solution; At least it works for Linux

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>