在Java中执行Linux命令有以下几种方法:
String command = "ls -a";
Process process = Runtime.getRuntime().exec(command);
// 获取命令执行的输出结果
InputStream inputStream = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// 等待命令执行完成
int exitCode = process.waitFor();
System.out.println("Exit code: " + exitCode);
List<String> command = Arrays.asList("ls", "-a");
ProcessBuilder processBuilder = new ProcessBuilder(command);
// 设置工作目录
processBuilder.directory(new File("/path/to/directory"));
// 执行命令
Process process = processBuilder.start();
// 获取命令执行的输出结果,等待命令执行完成
InputStream inputStream = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
int exitCode = process.waitFor();
System.out.println("Exit code: " + exitCode);
首先需要在项目中引入Apache Commons Exec库的依赖,然后可以使用CommandLine对象来执行命令。
CommandLine commandLine = new CommandLine("ls");
commandLine.addArgument("-a");
DefaultExecutor executor = new DefaultExecutor();
// 设置工作目录
executor.setWorkingDirectory(new File("/path/to/directory"));
// 执行命令
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
executor.setStreamHandler(streamHandler);
int exitCode = executor.execute(commandLine);
System.out.println(outputStream.toString());
System.out.println("Exit code: " + exitCode);
以上是三种常用的方法,可以根据需要选择适合的方法来执行Linux命令。