Ai
2 Star 3 Fork 1

汪少棠/java-se

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
RuntimeTest.java 14.62 KB
一键复制 编辑 原始数据 按行查看 历史
package org.example.se.lang;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import java.io.*;
/**
* 每一个JAVA程序实际上都是启动了一个JVM进程,每一个JVM进程都对应一个Runtime实例
*
* @author wangMaoXiong
* @version 1.0
* @date 2024/12/22 12:00
* @see org.example.uitls.RuntimeUtil
*/
public class RuntimeTest {
/**
* 错误示范:cmd 中有很多类似如下的指令,如目录统计:"dir"、文件(夹)复制:"copy"、删除文件:del 等等
*/
@Test
public void testErrorExample1() {
try {
Runtime runtime = Runtime.getRuntime();
// 这样运行会报错: java.io.IOException: Cannot run program "dir": CreateProcess error=2, 系统找不到指定的文件。
// 因为此时它默认把"dir"当做程序进行运行了;
runtime.exec("dir E:\\gxg");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 1、exec(String xxx),不加前缀时默认只能执行 windows 自带的程序或者可执行的 exe 文件,对于其它 cmd 指令必须调用 windows 的 cmd 程序来执行。
* 2、格式:exec("cmd /c xxx"):cmd 表示调用 windows 的 cmd 程序来执行后面的 "xxx" 指令,/c 是参数
* 3、无论什么指令,都建议加上"cmd /c",这是实际开发中常用的方式:
*/
@Test
public void testExec1() {
try {
Runtime runtime = Runtime.getRuntime();
// runtime.exec("cmd /c echo 123"); // 不会弹出 cmd 窗口,也不会一闪而过,直观上看不到任何东西
// runtime.exec("cmd /c dir E:\\gxg"); // 不会弹出 cmd 窗口,也不会一闪而过,直观上看不到任何东西
// runtime.exec("cmd /c E:\\jarDir\\test.jar"); // 可执行 jar 程序必须加"cmd /c"运行
// runtime.exec("cmd /c E:\\Study_Note\\html\\Html_in-depth.docx"); // 打开指定文档,也可以是其它格式,如png、jpg、pptx、pdf等等,会调用它们的默认程序来打开它们
// runtime.exec("cmd /c D:\\PotPlayer\\PotPlayerMini.exe"); // exe 程序前面加不加"cmd /c"都能正常运行
runtime.exec("cmd /c calc"); // windows 自带的程序前面加不加 cmd /c 都能正常运行
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* exec("cmd /c dir E:\\gxg"):它默认是不会弹出 cmd 面板的,如果希望它弹出时,则可以加上 "start" 参数 exec("cmd /c start dir E:\\gxg")
*/
@Test
public void testExec2() {
try {
Runtime runtime = Runtime.getRuntime();
// runtime.exec("cmd /c start echo 123"); // 弹出 cmd 框显示字符“123”
// runtime.exec("cmd /c start dir E:\\gxg"); // 弹出 cmd 框显示"E:\\gxg"目录的详细信息
// runtime.exec("cmd /c start E:\\xfmovie\\a.txt"); // 会打开 a.txt 文件,因为没有 cmd 输出内容,所以不会弹出 cmd 框,与不加 "start" 参数是一样的
runtime.exec("cmd /c start notepad"); // 会打开记事本,但不会弹出 cmd 框,与不加 "strat" 时一样
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* exec(String command,  String[] envp) 
* 1、在指定环境的单独进程中执行指定的字符串命令。 
* 2、参数:command - 一条指定的系统命令,其中可以设置变量,包括windows中的环境变量;
* 3、参数:envp - 字符串数组,其中每个元素的环境变量的设置格式为 name=value,name值为command中的变量名称;如果子进程应该继承当前进程的环境,或该参数为 null。 
* 4、返回:一个新的 Process 对象,用于管理子进程
* 5、通俗的讲就是在 exec(String command) 的基础上,加了可以为指令(command)动态设置变量值了。
*/
@Test
public void testExec3() {
try {
Runtime runtime = Runtime.getRuntime();
// 1、没有加"start"参数,所以并不会弹出cmd框,但是并不影响读取结果
// 2、%tartgetDir%类似windows环境变量的写法,变量必须用"%%"扣起来,后面字符串数组中用"key=value"的形式,key名称必须与前面的变量名称相同
Process process = runtime.exec("cmd /c dir %targetDir%", new String[]{"targetDir=F:\\Temp"});
InputStream inputStream = process.getInputStream();
// 3、将字节流转字符流并采用"gbk"编码,否则中文乱码,接着使用缓冲流读取数据
InputStreamReader streamReader = new InputStreamReader(inputStream, "gbk");
BufferedReader bufferedReader = new BufferedReader(streamReader);
String readLine;
while ((readLine = bufferedReader.readLine()) != null) {
System.out.println(readLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* exec(String command,  String[] envp) 
*/
@Test
public void testExec4() {
try {
Runtime runtime = Runtime.getRuntime();
// 可以直接获取windows系统的环境变量值
Process process = runtime.exec("cmd /c dir %JAVA_HOME%", null);
InputStream inputStream = process.getInputStream();
InputStreamReader streamReader = new InputStreamReader(inputStream, "gbk");
BufferedReader bufferedReader = new BufferedReader(streamReader);
String readLine;
while ((readLine = bufferedReader.readLine()) != null) {
System.out.println(readLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* exec(String command, String[] envp, File dir)
* 1、参数:dir - 子进程的工作目录;如果子进程应该继承当前进程的工作目录,则该参数为 null。 
* 2、通俗的讲就是在exec(String command,String[] envp)的基础上,加上了可以在指定目录执行子进程了。如下是没指定dir时,会以当前进程的工作目录执行。
*/
@Test
public void testExec5() {
try {
// WolCmd.exe 是一个网络唤醒工具,https://i-blog.csdnimg.cn/blog_migrate/a3121c2330dda0794fce9f10b0aa9f2f.png;
// 比如让它来唤醒其它电脑自动开机;只需要对方支持网络唤醒,则可以让它来实现开机;
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("cmd /c WolCmd.exe 1CB72CEFBA3D 192.168.1.20 255.255.255.0 100", null, new File("D:\\program"));
InputStream inputStream = process.getInputStream();
InputStreamReader streamReader = new InputStreamReader(inputStream, "gbk");
BufferedReader bufferedReader = new BufferedReader(streamReader);
String readLine;
while ((readLine = bufferedReader.readLine()) != null) {
System.out.println(readLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* exec(String[] cmdarray, String[] envp, File dir)
* 1、其它重载方法中的 command 参数适合程序路径、参数路径中不带空格的情况,如:"cmd /c del E:/wmx/log.txt"、"cmd /c D:\PotPlayer\PotPlayerMini.exe E:/wmx/zl2.mp4"
* 2、cmdarray 参数是 cmd 指令数组,适合程序、参数路径中带空格的情况,程序路径如“C:\Program Files (x86)\Microsoft Office\root\Office16\WINWORD.EXE”,或参数路径如“E:\wmx 笔记\Map in-depth.docx”。
* 3、envp:参数值,提供给command/cmdarray中参数的值
*/
@Test
public void testExec6() {
try {
// 指定cmd指令数组
// 只要有空格,则必须采用如下方式分开写。
// 用Runtime.exec(String command)方法是不行的
String[] paramArr = new String[2];
paramArr[0] = "C:\\Program Files (x86)\\Microsoft Office\\root\\Office16\\WINWORD.EXE";
paramArr[1] = "E:\\wmx\\Map_in-depth.docx";
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(paramArr);
// 10秒后,关闭WINWORD.EXE程序
Thread.sleep(10000);
if (process.isAlive()) {
process.destroy();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 打开指定的程序
* 如windows自带的:记事本程序 notepad、notepad.exe 计算器程序:calc、服务程序:services.msc 等等
* 以及安装的第三方程序:D:\Foxmail_7.2\Foxmail.exe、D:\software\WeChat\WeChat.exe 等等
* 如果被执行的程序支持传参,则打开程序的同时还可以传递参数,如打开potPlayer播放指定的视频:"D:\PotPlayer\PotPlayerMini.exe E:\xfmovie\WoxND7209-mobile.mp4"
* <p>
* !!!这种写法,经过反复实践验证后,通常只对 "windows自带的程序"、"*.exe"(写全路径)程序有效。
*
* @param appNameORPath:取值如上所示
*/
public static final void runExtApp(String appNameORPath) {
try {
Runtime runtime = Runtime.getRuntime();
runtime.exec(appNameORPath);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 复制文件
*
* @param sourcePath :源文件 或者 源目录(当时目录时,只会复制其下面子一级中的所有文件)
* @param targetPath :文件存放的目标目录或文件
* @return :true 或者 false
*/
public static final boolean copyPath(String sourcePath, String targetPath) {
boolean result = false;
try {
if (StringUtils.isBlank(sourcePath) || !new File(sourcePath).exists()) {
return result;
}
if (StringUtils.isBlank(targetPath)) {
return result;
}
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("cmd /c copy " + sourcePath + " " + targetPath);
InputStreamReader streamReader = new InputStreamReader(process.getInputStream(), "gbk");
BufferedReader bufferedReader = new BufferedReader(streamReader);
String readLine;
while ((readLine = bufferedReader.readLine()) != null) {
System.out.println(readLine);
}
result = true;
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* 复制目录:包括目录下所有子孙文件、文件夹
*
* @param sourcePath :源文件 或者 源目录(当时目录时,会复制其下面所有所以子孙文件和文件夹)
* @param targetPath :文件存放的目标目录或文件
* @return :true 或者 false
*/
public static final boolean copyDir(String sourcePath, String targetPath) {
boolean result = false;
try {
if (StringUtils.isBlank(sourcePath) || !new File(sourcePath).exists()) {
return result;
}
if (StringUtils.isBlank(targetPath)) {
return result;
}
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("cmd /c xcopy /e " + sourcePath + " " + targetPath);
InputStreamReader streamReader = new InputStreamReader(process.getInputStream(), "gbk");
BufferedReader bufferedReader = new BufferedReader(streamReader);
String readLine;
while ((readLine = bufferedReader.readLine()) != null) {
System.out.println(readLine);
}
result = true;
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* 删除文件:只支持删除文件,不支持删除文件夹
*
* @param sourcePath :源文件路径
* @return
*/
public static final boolean deleteFile(String sourcePath) {
boolean result = false;
try {
if (StringUtils.isBlank(sourcePath) || !new File(sourcePath).exists()) {
return result;
}
if (new File(sourcePath).isDirectory()) {
return result;
}
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("cmd /c del " + sourcePath);
InputStreamReader streamReader = new InputStreamReader(process.getInputStream(), "gbk");
BufferedReader bufferedReader = new BufferedReader(streamReader);
result = true;
String readLine;
while ((readLine = bufferedReader.readLine()) != null) {
System.out.println(readLine);
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* 删除文件夹:整个文件夹都会删除掉,包括自己以及下面所有子孙
*
* @param sourcePath :源文件路径
* @return
*/
public static final boolean deleteDir(String sourcePath) {
boolean result = false;
try {
if (StringUtils.isBlank(sourcePath) || !new File(sourcePath).exists()) {
return result;
}
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("cmd /c rd/s/q " + sourcePath);
InputStreamReader streamReader = new InputStreamReader(process.getInputStream(), "gbk");
BufferedReader bufferedReader = new BufferedReader(streamReader);
result = true;
String readLine;
while ((readLine = bufferedReader.readLine()) != null) {
System.out.println(readLine);
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
@Test
public void testDeleteFile() {
System.out.println(RuntimeTest.deleteFile("F:\\Temp\\sql2\\all.sql"));
}
@Test
public void testDeleteDir() {
System.out.println(RuntimeTest.deleteDir("F:\\Temp\\sql2"));
}
@Test
public void testCopyDir() {
System.out.println(copyDir("E:\\gxg\\wmx", "E:\\wmx"));
}
@Test
public void testCopyPath() {
System.out.println(copyPath("E:\\gxg\\wmx\\logs", "E:\\wmx"));
}
@Test
public void testRunExtApp() {
RuntimeTest.runExtApp("notepad");
// RuntimeTest.runExtApp("notepad.exe");
// RuntimeTest.runExtApp("calc");
// RuntimeTest.runExtApp("D:\\software\\WeChat\\WeChat.exe");
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/wangmx1993/java-se.git
git@gitee.com:wangmx1993/java-se.git
wangmx1993
java-se
java-se
master

搜索帮助