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

1.8k views Asked by At

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?

2

There are 2 answers

5
Joni On BEST ANSWER

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.

0
defender On

List item

The following program will work, initially it prints 10 lines , then press enter it will print next line till end of the file. run program like java Less $fileName

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class Less
{


    public static void main(String args[]) throws IOException
    {
        FileReader reader = new FileReader(args[0]);
        BufferedReader buff = new BufferedReader(reader);
        String readLine;
        int lineCount = 0;
        while ((readLine = buff.readLine()) != null)
        {
           System.out.println(readLine);
            lineCount++;
            if (lineCount > 10)
            { 
                Scanner scanner = new Scanner(System.in);
                scanner.nextLine();
            }
        }
     }
}