[英]Executing command in terminal from java programmatically
I have a requirement to execute a command in terminal using java. 我需要使用Java在终端中执行命令。 I am really stuck up to access terminal window of mac through java code programmatically. 我真的很想以编程方式通过java代码访问mac的终端窗口。 It would be really useful if you provide your valuable solutions to perform my task which i have been struggling to do for a past two days. 如果您提供有价值的解决方案来执行我过去两天一直在努力完成的任务,这将非常有用。 I am also posting the piece of code that I am trying to do for your reference. 我还发布了我想做的代码片段,以供您参考。 Any kind of help would be helpful for me 任何帮助都会对我有帮助
public class TerminalScript
{
public static void main(String args[]){
try {
Process proc = Runtime.getRuntime().exec("/Users/xxxx/Desktop/NewFolder/keytool -genkey -v -keystore test.keystore -alias test -keyalg RSA -sigalg SHA1withRSA -keysize 2048 -validity 10000");
BufferedReader read = new BufferedReader(new InputStreamReader(
proc.getInputStream()));
try {
proc.waitFor();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
while (read.ready()) {
System.out.println(read.readLine());
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
Note: I have to run the command keytool -genkey -v -keystore test.keystore -alias test -keyalg RSA -sigalg SHA1withRSA -keysize 2048 -validity 10000
in terminal through java program. 注意:我必须通过Java程序在终端中运行命令keytool -genkey -v -keystore test.keystore -alias test -keyalg RSA -sigalg SHA1withRSA -keysize 2048 -validity 10000
。
There are a number of problems with your code: 您的代码有很多问题:
keytool
sends its prompts to stderr
, not stdout
, so you need to call proc.getErrorStream()
keytool
将其提示发送到stderr
而不是stdout
,因此您需要调用proc.getErrorStream()
keytool
as you need to see the prompts 您不想缓冲keytool
的输出,因为您需要查看提示 keytool
to terminate 您不想等待keytool
终止 keytool
is interactive, you need to read from and write to the process. 由于keytool
是交互式的,因此您需要对过程进行读取和写入。 It might be better to spawn separate threads to handle the input and output separately. 最好生成单独的线程来分别处理输入和输出。 The following code addresses the first three points as a proof of concept and will show the first prompt from keytool, but as @etan-reisner says, you probably want to use the native APIs instead. 以下代码作为概念证明解决了前三点,并且将显示keytool的第一个提示,但是正如@ etan-reisner所说,您可能想使用本机API。
Process proc = Runtime.getRuntime().exec("/usr/bin/keytool -genkey -v -keystore test.keystore -alias test -keyalg RSA -sigalg SHA1withRSA -keysize 2048 -validity 10000");
InputStream read = proc.getErrorStream();
while (true) {
System.out.print((char)read.read());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.