[英]put the output of the shell script into a variable in a Java program
有没有一种方法可以将Shell脚本程序的输出转换为Java程序中的变量(而不转换为输出文件)。 我的Shell脚本的输出是数据库查询执行时间,我需要将该时间值分配给Java变量。 (我正在从Java程序中调用该Shell脚本)。 然后,我将需要对Java中的这些值进行其他一些计算。
下面的程序将帮助您将任何脚本或任何命令的完整输出存储到String对象中。
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ExecuteShellComand {
public static void main(String[] args) {
ExecuteShellComand obj = new ExecuteShellComand();
String output = obj.executeCommand("sh /opt/yourScriptLocation/Script.sh");
System.out.println(output);
}
private String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
}
我只是用谷歌搜索,这里有一个很好的教程,上面有很多例子: http : //www.mkyong.com/java/how-to-execute-shell-command-from-java/
我知道人们喜欢复制/粘贴,但让我们尊重他人的工作并访问他们的网站:p
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.