CommandUtil.java
package com.lanying.util;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class CommandUtil {
public static String run(String command, File dir) throws IOException {
Scanner input = null;
StringBuilder result = new StringBuilder(command + "\n"); // 加上指令本身
Process process = null;
try {
process = Runtime.getRuntime().exec(command, null, dir);
try {
//等待指令執行完成
process.waitFor(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
InputStream is = process.getInputStream();
input = new Scanner(is);
while (input.hasNextLine()) {
result.append(input.nextLine() + "\n");
}
} finally {
if (input != null) {
input.close();
}
if (process != null) {
process.destroy();
}
}
return result.toString();
}
public static List run(String[] command, File dir) throws IOException {
BufferedReader in = null;
PrintWriter out = null;
List resultList = new ArrayList();
Process process = null;
try {
// 開啟腳本是為了能夠擷取所有的傳回結果
process = Runtime.getRuntime().exec("/bin/sh", null, dir); // /bin/sh開啟shell腳本
in = new BufferedReader(new InputStreamReader(process.getInputStream()));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(process.getOutputStream())), true);
for (String cmd : command) {
out.println(cmd); // 一條條執行指令
}
out.println("exit"); // 表示腳本結束,必須執行,否則in流不結束。
try {
// 等待指令執行完成
process.waitFor(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 裝填傳回結果,比如ls指令執行後顯示的一行行字元串
String line = "";
while ((line = in.readLine()) != null) {
resultList.add(line);
}
resultList.add(0, Arrays.toString(command)); // 加上指令本身,可根據需要自行取舍
} finally {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
if (process != null) {
process.destroy();
}
}
return resultList;
}
}
JUnitRuntimeExec.java
package com.lanying.demo;
import com.lanying.util.CommandUtil;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class JUnitRuntimeExec {
@Test
public void testCMD(){
File dir = new File("/lanying");
try {
String res = CommandUtil.run("ls -l",dir);
System.out.println(res);
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testCMDList(){
// 在該目錄下執行指令
File dir = new File("/lanying");
List cmdList = new ArrayList<>();
cmdList.add("ls -lrt");
cmdList.add("ls -lrt");
try {
// 執行指令
List res = CommandUtil.run(cmdList.toArray(new String[cmdList.size()]),dir);
// 周遊結果
res.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
}
執行效果:
Java程式執行單條Linux指令效果圖.png
Java程式執行多條Linux指令效果圖.png
參考資料:
本文位址:https://blog.csdn.net/lanying100/article/details/107352792
希望與廣大網友互動??
點此進行留言吧!