yumi
yumi

Reputation: 153

System command fail to execute from program

I had tested the following methods to execute Linux command from my program

Method 1 : Assign all into a string

String temp1 = "'/"+t2+"/,/"+t1+"/p'";
String command2 = "sed -n "+temp1+" app.log";
Process p1 = Runtime.getRuntime().exec(command2);



Method 2 : use array

String [] command2 = new String []{"sed","-n","'/",t2,"/,/",t1,"/p'", "app.log";
System.out.println("The command2 is : "+Arrays.toString(command2);
Process p2 = new ProcessBuilder(command2).start();



This my reference link for the method 2 but both of the methods not working at all. This is the command I hope to run in the terminal
sed -n '/14:32:54/,/14:33:44/p' app.log

This is a portion of my code for calling the system command, nothing displayed in line2 variable

String [] command2 = new String []{"sed","-n","'/",t2,"/,/",t1,"/p'","stlog.txt"};
Process p2 = new ProcessBuilder(command2).start();
BufferedReader br2 = new BufferedReader(new InputStreamReader(p2.getInputStream()));
String line2;
while((line2 = br2.readLine()) != null)
   {
      System.out.println(line2);
   }

Upvotes: 0

Views: 189

Answers (1)

Vitaliy Moskalyuk
Vitaliy Moskalyuk

Reputation: 2583

In my case worked:

 ProcessBuilder processBuilder = new ProcessBuilder("/bin/bash", "-c", "pwd")
                    .directory(new File("some.directory.path"));
 Process process = processBuilder.start();

Or you can sip using ProcessBuilder and just call

String command = "ping www.google.com";
String[] commandArray = {"/bin/bash", "-c", "pwd"}; 
Runtime.getRuntime().exec(commandArray);

"/bin/bash" 0 means that you are going to exec command in bach

"-c" -defines that next param is command

command - any command like "ping www.google.com" or "./script.sh" that you execute with terminal

you should just place your command instead of "ping www.google.com", but as you haven't specified directory - script will be executed from project directory (you can check it by executing "pwd" command that prints current directory). That is why ProcessBuilder is more preferable, as you can indicate execution directory there (replace "some.directory.path" with your dir).

.directory(new File("path/to/some/dir"));

Upvotes: 1

Related Questions