1、利用java调用cmd命令打开文件。
调用方法使用
/**
* 执行系统命令并返回命令的输出。
*
* @param command 要执行的系统,这里写路径,如D:\qq\QQ.exe
* @return 执行命令后的输出字符串。
* @throws IOException 如果执行命令过程中发生I/O错误。
*/
public static String executeCmd(String command) throws IOException {
// 获取运行时环境
// 在单独的进程中执行指定的外部可执行程序的启动路径或字符串命令
Runtime runtime = Runtime.getRuntime();
// 执行命令
Process process = runtime.exec(command);
// 以UTF-8编码读取命令的输出流
BufferedReader br = new BufferedReader(new
InputStreamReader(process.getInputStream(), "UTF-8"));
String line = null;
StringBuilder build = new StringBuilder();
while ((line = br.readLine()) != null) {
// 将读取的每一行命令输出追加到字符串构建器中
build.append(line);
}
// 返回拼接后的所有命令输出
return build.toString();
}
2、ProcessBuilder调用cmd方式。
/**
* 启动指定路径的程序。
*
* @param programPath 程序的文件路径。必须是有效的文件路径,且路径中包含文件名和扩展名。
* @throws IOException 如果启动程序过程中发生I/O错误。
*/
public static void startProgram(String programPath) throws IOException {
// 检查程序路径是否为空或仅包含空白字符
if (StringUtils.isNotBlank(programPath)) {
try {
// 从程序路径中提取程序名(不包括扩展名)
String programName = programPath
.substring(programPath.lastIndexOf("/") + 1, programPath.lastIndexOf("."));
// 创建一个列表,包含启动程序所需的命令行参数
List<String> list = new ArrayList<String>();
list.add("cmd.exe");
list.add("/c");
list.add("start");
list.add("\"" + programName + "\"");
list.add("\"" + programPath + "\"");
// 使用ProcessBuilder启动程序
ProcessBuilder pBuilder = new ProcessBuilder(list);
pBuilder.start();
} catch (Exception e) {
// 如果启动程序失败,打印堆栈跟踪
e.printStackTrace();
}
}
}
3、通过调用Desktop类的open方法,尝试打开传入路径指向的应用程序。
执行代码前确保未设置无头模式,不认就用上面两种方法。
/**
* 启动指定路径的应用程序。
*
* 通过调用Desktop类的open方法,尝试打开传入路径指向的应用程序。
* 如果应用程序不存在或无法打开,将打印堆栈跟踪信息。
*
* @param programPath 应用程序的路径。如果路径为空或不明确,则不执行任何操作。
* @throws IOException 如果打开文件失败,则抛出此异常。
*/
public static void startProgram(String programPath) throws IOException {
// 检查程序路径是否为空或模糊
if (StringUtils.isNotBlank(programPath)) {
try {
// 尝试打开指定路径的应用程序
File file = new File(programPath);
Desktop.getDesktop().open(file);
} catch (Exception e) {
// 如果出现异常,打印堆栈跟踪
e.printStackTrace();
}
}
}