Poonam Hoshi
Poonam Hoshi

Reputation: 71

Executing linux commands from inside java program

I am trying to create a GUI using java swing. From there I have to run linux system commands. I tried using exec(). But the exec() function is unable to parse the string if it contains single quotes. The code which I have used is as follows-

Process p = Runtime.getRuntime().exec("cpabe-enc pub_key message.txt '( it_department or ( marketing and manager ) )'")
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

But I am getting error when I run the program as--syntax error at "'(".

The same command runs when I write

Process p = Runtime.getRuntime().exec("cpabe-enc pub_key message.txt default")

Please help. Thanks in advance for your help.

Upvotes: 0

Views: 1568

Answers (3)

Dhruv
Dhruv

Reputation: 10703

I recently got this kind of problem solved. I was using javaFX to call shell scripts on button click .. which is very much similar to your swing application scenario...

Here are the links hope it might help you...

How to code in java to run unix shell script which use rSync internally in windows environment using cygwin?

Getting error in calling shell script in windows environment using java code and cygwin...!

Happy coding... :)

Upvotes: 0

Mattias Isegran Bergander
Mattias Isegran Bergander

Reputation: 11909

Split up the parameters into an array instead, one string for each argument, and use the exec-method that takes as String[] instead, that generally works better for arguments. Somethign along the lines of:

Runtime.getRuntime().exec(new String[] {"cpabe-enc", "pub_key", "message.txt", "( it_department or ( marketing and manager ) )"});

or whatever what your exact parameters are.

Upvotes: 1

barsju
barsju

Reputation: 4446

Its because the runtime does not interpret the '(...)' as a single parameter like you intend.

Try using ProcessBuilder instead: http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ProcessBuilder.html

Upvotes: 0

Related Questions