在Java中,你可以使用Runtime
类或ProcessBuilder
类来执行Linux命令
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
try {
String command = "ls"; // 这里可以替换为你想要执行的Linux命令
Process process = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
process.waitFor();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
try {
String[] command = {"ls", "-la"}; // 这里可以替换为你想要执行的Linux命令和参数
ProcessBuilder processBuilder = new ProcessBuilder(Arrays.asList(command));
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
process.waitFor();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
注意:在使用这些方法时,请确保你的应用程序具有执行Linux命令所需的权限。如果你在非Linux系统上运行此代码,可能需要使用跨平台的命令。