简体   繁体   English

从Java程序内部执行linux命令

[英]Executing linux commands from inside java program

I am trying to create a GUI using java swing. 我正在尝试使用Java swing创建GUI。 From there I have to run linux system commands. 从那里我必须运行linux系统命令。 I tried using exec(). 我尝试使用exec()。 But the exec() function is unable to parse the string if it contains single quotes. 但是,如果exec()函数包含单引号,则无法解析该字符串。 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. 在此先感谢您的帮助。

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. 而是将参数拆分为一个数组,每个参数一个字符串,然后使用采用String[]的exec方法,通常对参数更好。 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. 或您的确切参数是什么。

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 尝试改用ProcessBuilder: http : //docs.oracle.com/javase/1.5.0/docs/api/java/lang/ProcessBuilder.html

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... 我正在使用javaFX在按钮单击..时调用shell脚本,这与您的swing应用程序场景非常相似...

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? 如何在Java中编写代码以运行在Windows环境中使用cygwin内部使用rSync的unix shell脚本?

Getting error in calling shell script in windows environment using java code and cygwin...! 在Windows环境中使用Java代码和cygwin调用Shell脚本时出错...!

Happy coding... :) 快乐的编码... :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM