How to do less with swap from a Java console application?

I need to execute a less command with paging from my console Java application. However, the only way I found to execute external commands is Runtime.getRuntime().exec() , which requires me to write / read I / O through streams. So commands like cat work (and less really act like cat ), but I need swap functions.

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

Is there any way to do this in Java?

+4
source share
2 answers

When executing an external process with Runtime.exec() its standard input and output streams do not connect to the terminal from which you run the Java program. You can use shell redirection to connect it, but first you need to know which terminal to use. It is not possible to find a terminal using the standard API, but you can probably find an open source library that does this.

To make sure this can be done, this program opens 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 must use java Test $(tty) . The tty program prints the name of the terminal connected to its stdin.

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

+1
source

List item

The next program will work, initially it prints 10 lines, then press the enter key, and it will print the next line to the end of the file. run a program like java Less than $ 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(); } } } } 
0
source

Source: https://habr.com/ru/post/1393774/


All Articles