Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute "less" with paging from a Java console application?

I need to execute the less command, with paging, from my Java console application. However, the only method I found to execute external commands is Runtime.getRuntime().exec(), which requires me to write/read input/output via streams. So commands like cat work (and less does in fact act like cat), but I need the paging functionality.

In C, I'd use system(). In Ruby, Kernel.exec does the job.

Is there any way to get this done in Java?

like image 970
futlib Avatar asked Nov 04 '22 06:11

futlib


1 Answers

When you execute an external process with Runtime.exec() its standard input and output streams are not connected to the terminal from which you are running the Java program. You can use shell redirection to connect it, but first you need to know what terminal to use. There is no way to find the terminal using the standard API but probably you can find an open source library that does it.

To see that it can be done, this program opens itself in less:

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 stdin.

I'm not too sure about the portability of this solution; at least it works on Linux.

like image 113
Joni Avatar answered Nov 07 '22 21:11

Joni