业务需要,要求程序实现指定磁盘挂载功能。该功大致实现思路为使用java调用命令行工具,再利用命令行发送命令请求。其中命令又分为交互式命令和非交互式命令两类,后续有空打算直接将这俩类方法合并为更通用的方法。以下为命令行工具类具体代码实现:
package com.lyb.demo;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
/**
* 命令行工具类
*
* @author lyb
* @date 2023/12/19
*/
@Slf4j
public class CommandUtils {
private static final String MSG_EXEC_LINE = "-----------------command exec msg : {}";
private static final String MSG_RET_CODE = "-----------------command ret code : {}";
public static void exec(String[] commands) {
try {
ProcessBuilder pb = new ProcessBuilder();
pb.command(commands);
pb.redirectErrorStream(true);
Process p = pb.start();
String line;
BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = stdout.readLine()) != null) {
log.info(MSG_EXEC_LINE, line);
}
int retCode = p.waitFor();
log.info(MSG_RET_CODE, retCode);
stdout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void execWithInteraction(String dirPath, String[] commands, String params) {
try {
ProcessBuilder pb = new ProcessBuilder(commands);
if (StrUtil.isNotBlank(dirPath)) {
pb.directory(new File(dirPath));
}
pb.redirectErrorStream(true);
Process p = pb.start();
Writer writer = new OutputStreamWriter(p.getOutputStream());
writer.write(params);
writer.flush();
writer.close();
int retCode = p.waitFor();
log.info(MSG_RET_CODE, retCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}