Java - executing a command at runtime

I tried a simple program to execute a Linux command at runtime. But the following program compiles and runs without any error, but the text file is not created as intended. Is there something wrong with this program?

import java.io.*; class ExecuteJava { public static void main(String args[]) { String historycmd = "cat ~/.bash_history >> Documents/history.txt"; try { Runtime runtime = Runtime.getRuntime(); Process proc = runtime.exec(historycmd); } catch(Exception e) { System.out.println(e); } } } 
+4
source share
2 answers

The append >> operator is intended to be interpreted as part of the shell. Use

 String[] historycmd = { "bash", "-c", "cat ~/.bash_history >> Documents/history.txt"}; 
+1
source

Try some of the features of Process . I would start with exitValue . As a rule, -1 indicates that something went wrong, and 0 means that nothing special happened.

Also try InputStream and Stream Error , and read them completely. See if you have any useful feedback.

Other than that, try specifying andy256 in the comments. Make sure that the Documents directory exists in the executable directory of the program.

+2
source

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


All Articles