从Java运行Unix命令非常简单。
Runtime.getRuntime().exec(myCommand);
但是有可能从Java代码运行Unix shell脚本吗?如果是,从Java代码中运行Shell脚本是一个好习惯吗?
从Java运行Unix命令非常简单。
Runtime.getRuntime().exec(myCommand);
但是有可能从Java代码运行Unix shell脚本吗?如果是,从Java代码中运行Shell脚本是一个好习惯吗?
Answers:
您应该真正看一下Process Builder。它确实是为这种事情而构建的。
ProcessBuilder pb = new ProcessBuilder("myshellScript.sh", "myArg1", "myArg2");
Map<String, String> env = pb.environment();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
pb.directory(new File("myDir"));
Process p = pb.start();
您也可以使用Apache Commons exec库。
范例:
package testShellScript;
import java.io.IOException;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
public class TestScript {
int iExitValue;
String sCommandString;
public void runScript(String command){
sCommandString = command;
CommandLine oCmdLine = CommandLine.parse(sCommandString);
DefaultExecutor oDefaultExecutor = new DefaultExecutor();
oDefaultExecutor.setExitValue(0);
try {
iExitValue = oDefaultExecutor.execute(oCmdLine);
} catch (ExecuteException e) {
System.err.println("Execution failed.");
e.printStackTrace();
} catch (IOException e) {
System.err.println("permission denied.");
e.printStackTrace();
}
}
public static void main(String args[]){
TestScript testScript = new TestScript();
testScript.runScript("sh /root/Desktop/testScript.sh");
}
}
为了进一步参考,还在Apache Doc上给出了一个示例。
OutputStream
为DefaultExecuter
使用DefaultExecuter.setStreamHandler
方法在捕获输出OutputStream
。请参考该线程以获取更多信息:我如何捕获命令的输出...
我要说的是,从Java运行Java的Shell脚本不是Java 的精神。Java被认为是跨平台的,运行shell脚本会将其使用范围限制为仅UNIX。
话虽如此,从Java内部运行Shell脚本绝对是可能的。您将使用与列出的语法完全相同的语法(我自己没有尝试过,但是尝试直接执行shell脚本,如果不行,请执行shell本身,将脚本作为命令行参数传入) 。
switches
和if
语句来解决所有不尽管谁与Java核心类库想出了人民的最大努力工作,在不同平台上完全相同的细微差别。
我认为您已经回答了自己的问题
Runtime.getRuntime().exec(myShellScript);
关于这是否是一种好习惯……您打算如何处理Java无法使用的shell脚本?
是的,可以这样做。这为我解决了。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.omg.CORBA.portable.InputStream;
public static void readBashScript() {
try {
Process proc = Runtime.getRuntime().exec("/home/destino/workspace/JavaProject/listing.sh /"); //Whatever you want to execute
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());
}
}
这是我的例子。希望有道理。
public static void excuteCommand(String filePath) throws IOException{
File file = new File(filePath);
if(!file.isFile()){
throw new IllegalArgumentException("The file " + filePath + " does not exist");
}
if(isLinux()){
Runtime.getRuntime().exec(new String[] {"/bin/sh", "-c", filePath}, null);
}else if(isWindows()){
Runtime.getRuntime().exec("cmd /c start " + filePath);
}
}
public static boolean isLinux(){
String os = System.getProperty("os.name");
return os.toLowerCase().indexOf("linux") >= 0;
}
public static boolean isWindows(){
String os = System.getProperty("os.name");
return os.toLowerCase().indexOf("windows") >= 0;
}
为了避免必须对绝对路径进行硬编码,可以使用以下方法来查找并执行脚本(如果该脚本位于根目录中)。
public static void runScript() throws IOException, InterruptedException {
ProcessBuilder processBuilder = new ProcessBuilder("./nameOfScript.sh");
//Sets the source and destination for subprocess standard I/O to be the same as those of the current Java process.
processBuilder.inheritIO();
Process process = processBuilder.start();
int exitValue = process.waitFor();
if (exitValue != 0) {
// check for errors
new BufferedInputStream(process.getErrorStream());
throw new RuntimeException("execution of script failed!");
}
}
对于我来说,所有事情都必须简单。对于运行脚本,只需执行
new ProcessBuilder("pathToYourShellScript").start();
的ZT处理执行库是Apache的百科全书Exec的一种替代方法。它具有运行命令,捕获命令输出,设置超时等功能。
我还没有使用过它,但是它看起来有据可查。
文档中的示例:执行命令,将stderr泵到记录器,将输出作为UTF8字符串返回。
String output = new ProcessExecutor().command("java", "-version")
.redirectError(Slf4jStream.of(getClass()).asInfo())
.readOutput(true).execute()
.outputUTF8();
它的文档列出了Commons Exec的以下优点:
这是一个如何从Java运行Unix bash或Windows bat / cmd脚本的示例。可以在脚本上传递参数,并从脚本接收输出。该方法接受任意数量的参数。
public static void runScript(String path, String... args) {
try {
String[] cmd = new String[args.length + 1];
cmd[0] = path;
int count = 0;
for (String s : args) {
cmd[++count] = args[count - 1];
}
Process process = Runtime.getRuntime().exec(cmd);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
try {
process.waitFor();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
while (bufferedReader.ready()) {
System.out.println("Received from script: " + bufferedReader.readLine());
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
System.exit(1);
}
}
在Unix / Linux上运行时,路径必须类似于Unix(以'/'作为分隔符),而在Windows上运行时,请使用'\'。Hier是一个bash脚本(test.sh)的示例,该脚本接收任意数量的参数并将每个参数加倍:
#!/bin/bash
counter=0
while [ $# -gt 0 ]
do
echo argument $((counter +=1)): $1
echo doubling argument $((counter)): $(($1+$1))
shift
done
打电话时
runScript("path_to_script/test.sh", "1", "2")
在Unix / Linux上,输出为:
Received from script: argument 1: 1
Received from script: doubling argument 1: 2
Received from script: argument 2: 2
Received from script: doubling argument 2: 4
Hier是一个简单的cmd Windows脚本test.cmd,它计算输入参数的数量:
@echo off
set a=0
for %%x in (%*) do Set /A a+=1
echo %a% arguments received
在Windows上调用脚本时
runScript("path_to_script\\test.cmd", "1", "2", "3")
输出是
Received from script: 3 arguments received
String scriptName = PATH+"/myScript.sh";
String commands[] = new String[]{scriptName,"myArg1", "myArg2"};
Runtime rt = Runtime.getRuntime();
Process process = null;
try{
process = rt.exec(commands);
process.waitFor();
}catch(Exception e){
e.printStackTrace();
}
这是一个较晚的答案。但是,我想到了要为将来的开发人员从Spring-Boot应用程序中执行Shell脚本而付出的努力。
我在Spring-Boot中工作,但无法从Java应用程序中找到要执行的文件,并且该文件正在throw FileNotFoundFoundException
。我必须将文件保留在resources
目录中,并且必须设置要在pom.xml
启动应用程序时扫描的文件,如下所示。
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
<include>**/*.sh</include>
</includes>
</resource>
</resources>
error code = 13, Permission Denied
。然后我必须通过运行此命令使文件可执行-chmod u+x myShellScript.sh
最后,我可以使用以下代码片段执行文件。
public void runScript() {
ProcessBuilder pb = new ProcessBuilder("src/main/resources/myFile.sh");
try {
Process p;
p = pb.start();
} catch (IOException e) {
e.printStackTrace();
}
}
希望能解决某人的问题。
供Linux使用
public static void runShell(String directory, String command, String[] args, Map<String, String> environment)
{
try
{
if(directory.trim().equals(""))
directory = "/";
String[] cmd = new String[args.length + 1];
cmd[0] = command;
int count = 1;
for(String s : args)
{
cmd[count] = s;
count++;
}
ProcessBuilder pb = new ProcessBuilder(cmd);
Map<String, String> env = pb.environment();
for(String s : environment.keySet())
env.put(s, environment.get(s));
pb.directory(new File(directory));
Process process = pb.start();
BufferedReader inputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedWriter outputReader = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
int exitValue = process.waitFor();
if(exitValue != 0) // has errors
{
while(errReader.ready())
{
LogClass.log("ErrShell: " + errReader.readLine(), LogClass.LogMode.LogAll);
}
}
else
{
while(inputReader.ready())
{
LogClass.log("Shell Result : " + inputReader.readLine(), LogClass.LogMode.LogAll);
}
}
}
catch(Exception e)
{
LogClass.log("Err: RunShell, " + e.toString(), LogClass.LogMode.LogAll);
}
}
public static void runShell(String path, String command, String[] args)
{
try
{
String[] cmd = new String[args.length + 1];
if(!path.trim().isEmpty())
cmd[0] = path + "/" + command;
else
cmd[0] = command;
int count = 1;
for(String s : args)
{
cmd[count] = s;
count++;
}
Process process = Runtime.getRuntime().exec(cmd);
BufferedReader inputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedWriter outputReader = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
int exitValue = process.waitFor();
if(exitValue != 0) // has errors
{
while(errReader.ready())
{
LogClass.log("ErrShell: " + errReader.readLine(), LogClass.LogMode.LogAll);
}
}
else
{
while(inputReader.ready())
{
LogClass.log("Shell Result: " + inputReader.readLine(), LogClass.LogMode.LogAll);
}
}
}
catch(Exception e)
{
LogClass.log("Err: RunShell, " + e.toString(), LogClass.LogMode.LogAll);
}
}
和使用;
ShellAssistance.runShell("", "pg_dump", new String[]{"-U", "aliAdmin", "-f", "/home/Backup.sql", "StoresAssistanceDB"});
要么
ShellAssistance.runShell("", "pg_dump", new String[]{"-U", "aliAdmin", "-f", "/home/Backup.sql", "StoresAssistanceDB"}, new Hashmap<>());