JAVA:调用cmd指令(支持多次手工输入)
JDK开发环境:1.8
package com.le.tool; import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.Charset; /**
* java调用cmd指令工具类
*
* @author le.li
*
*/
public class ExecuteUtil {
/**
* 避免乱码,如果没有传入语言编号,默认使用英文437<br>
* D:\>chcp /? 显示或设置活动代码页编号。<br>
* CHCP [nnn]<br>
* nnn 指定代码页编号。<br>
* 不带参数键入 CHCP 以显示活动代码页编号。<br>
*/
private static final String DEFAULT_LANGUAGE_CODE = "437"; /**
* window系统默认语言:GBK
*/
private static final String DEFAULT_LANGUAGE = "GBK"; public static void main(String[] args) {
// executeLink(); // executeCmd("dir ."); // 举例直接把bat文件当cmd指令调用
String cmd = null;
String fileName = "test.bat";
File f = new File(".");
try {
cmd = f.getCanonicalPath() + File.separator + fileName;
} catch (IOException e) {
// e.printStackTrace();
System.err.println("get cmd file error.");
}
executeCmd(cmd);
} /**
* 获取操作系统默认语言
*
* @return String
* @see java虚拟机启动默认的编码(一般和java文件设置格式一致)<br>
* System.out.println(Charset.defaultCharset());<br>
* 查看预置的变量信息:System.getProperties().list(System.out);<br>
* 属性:<br>
* 文件编码:file.encoding<br>
* 系统默认编码sun.jnu.encoding
*/
private static String getsystemLanguage() {
return null == System.getProperty("sun.jnu.encoding") ? DEFAULT_LANGUAGE
: System.getProperty("sun.jnu.encoding");
} /**
* 执行cmd指令
* @param cmd 执行指令
*/
public static void executeCmd(String cmd) {
executeLink(DEFAULT_LANGUAGE_CODE, true, cmd);
} /**
* cmd手工输入交互处理窗口
*/
public static void executeLink() {
executeLink(DEFAULT_LANGUAGE_CODE, false, "");
} /**
* cmd交互处理窗口
*
* @param languageCode 系统语言编码
* @param isOneRun 只执行cmd指令
* @param cmd 执行的指令
* @see 在中文windows系统中,根据编码需要设置编码 chcp 65001 就是换成UTF-8代码页<br>
* chcp 936 可以换回默认的GBK<br>
* chcp 437 是美国英语 <br>
*/
public static void executeLink(String languageCode, boolean isOneRun, String cmd) {
try {
String cmdBin = "cmd";
if (isOneRun) {
cmdBin = "cmd /c ";
}
Process process = Runtime.getRuntime().exec(cmdBin + cmd);
PrintWriter writer = new PrintWriter(process.getOutputStream());
if (!isOneRun) {
// 此处可以预置交互指令
// writer.println("chcp " + languageCode);
writer.println("echo Hello World.");
writer.flush();
}
CommandThread commandThread = new CommandThread(writer);
commandThread.setName("ExecuteCmdThread");
commandThread.start();
ProcessInputStreamThread inputThread = new ProcessInputStreamThread(process.getInputStream());
ProcessInputStreamThread errorThread = new ProcessInputStreamThread(process.getErrorStream());
inputThread.setName("InputStreamThread");
inputThread.start();
errorThread.setName("ErrorStreamThread");
errorThread.start();
// 即使添加下边的一句也不会使线程结束
// Thread.currentThread().interrupt();
} catch (Exception e) {
e.printStackTrace();
}
} static class CommandThread extends Thread {
PrintWriter writer;
BufferedReader br = null; CommandThread(PrintWriter writer) {
this.writer = writer;
// 避免出现乱码问题,直接使用系统默认的编码格式
br = new BufferedReader(new InputStreamReader(System.in, Charset.forName(getsystemLanguage())));
this.setDaemon(true);
} @Override
public void run() {
try {
String cmd = null;
while ((cmd = br.readLine()) != null) {
writer.println(cmd);
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != writer) {
writer.close();
}
if (null != br) {
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
} static class ProcessInputStreamThread extends Thread { InputStream input;
BufferedReader breader = null; ProcessInputStreamThread(InputStream input) {
this.input = input;
// 避免出现乱码问题,直接使用系统默认的编码格式
breader = new BufferedReader(new InputStreamReader(input, Charset.forName(getsystemLanguage())));
} @Override
public void run() {
try {
String str = null;
while ((str = breader.readLine()) != null) {
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != input) {
try {
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (null != breader) {
try {
breader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
JAVA:调用cmd指令(支持多次手工输入)的更多相关文章
- java调用cmd执行maven命令
一.原理介绍 Java的Runtime.getRuntime().exec(commandStr)可以调用执行cmd指令. cmd /c dir 是执行完dir命令后封闭命令窗口. cmd /k di ...
- Java调用CMD命令
java的Runtime.getRuntime().exec(commandStr)可以调用执行cmd指令. cmd /c dir 是执行完dir命令后关闭命令窗口. cmd /k dir 是执行完d ...
- Java调用cmd命令 打开一个站点
使用Java程序打开一个站点 近期做了个东西使用SWT技术在一个client程序 须要升级时在提示升级 点击窗口上的一个连接 打开下载网页 花费了我非常长时间 用到了把它记录下来 怕是忘记,须要时能 ...
- Java 调用cmd.exe命令
原理:java的Runtime.getRuntime().exec(commandText)可以调用执行cmd指令. cmd /c dir 是执行完dir命令后关闭命令窗口. cmd /k dir 是 ...
- Java调用cmd压缩文件
今天在做一个java调用windows的压缩命令时遇到一奇怪问题代码如下: String cmd ="C:/Program Files (x86)/WinRAR/rar.exe a c:/t ...
- Spark(四十四):使用Java调用spark-submit.sh(支持 --deploy-mode client和cluster两种方式)并获取applicationId
之前也介绍过使用yarn api来submit spark任务,通过提交接口返回applicationId的用法,具体参考<Spark2.3(四十):如何使用java通过yarn api调度sp ...
- java调用cmd命令删除文件夹及其所有内容
/** * *删除D盘下面test目录,感觉以前用io流遍历删除好慢! * **/ public static void main(String[] args) { Runtime run = Run ...
- java 调用cmd命令
public class Port{ public static void main(String[] args) { Runtime runtime=Runtime.getRuntime(); tr ...
- Java调用windows命令
JAVA调用windows的cmd命令 用起来会让程序变得更加简洁明了,非常实用. 核心就是使用 Runtime类. cmd的xcopy就有很强大的文件夹,文件处理功能. 下面就以xcopy来说明,如 ...
随机推荐
- curl -d中的json存在引号怎么处理?
1\将其改写为I'\''m就可以执行 2\ curl -u elastic:mypass -X GET "localhost:9200/_analyze?pretty" -d 'a ...
- [Solution] 821. Shortest Distance to a Character
Difficulty: Easy Problem Given a string S and a character C, return an array of integers representin ...
- His表(简化)
门诊登记,门诊结算,门诊处方,住院登记,住院结算,住院处方,转诊登记,人员表,行政区划,登录日志,菜单,疾病,药品,诊疗,数据字典,机构,科室等
- Spring:事务
摘要 本文摘抄了Spring事务相关的一些理论,主要讲述事务的特性.事务的传播行为.事务的隔离规则. 关键词:事务特性,事务传播,事务隔离 一.什么是事务 事务是用来保证数据的完整性和一致性,正如金钱 ...
- python_1_基础知识
数据类型: 整数 浮点数 字符串 布尔值:True/False 空值:None 变量 常量 int(整型):在Python3里不再有long类型了,全都是int -2**63-2**63-1即-922 ...
- Hillstone设备管理-恢复出厂设置
1.CLI命令行操作 unset all: 根据提示选择是否保存当前配置y/n: 选择是否重启y/n: 系统重启后即恢复到出厂设置. 2.webUI操作 “系统”—“配置”,点击“清除”按钮,系统会提 ...
- centos7安装zabbix server
1.参照下列网址方法,打开端口:80,3306,443,22,10050,10051(可能实际不需要打开这么多) https://www.cnblogs.com/lw-2019forlinuxpyth ...
- centos7 使用kubeadm 快速部署 kubernetes 国内源
前言 搭建kubernetes时看文档以及资料走了很多弯路,so 整理了最后成功安装的过程已做记录.网上的搭建文章总是少一些步骤,想本人这样的小白总是部署不成功(^_^). 准备两台或两台以上的虚拟机 ...
- mysql执行计划id为空—UNION关键字
简介 UNION 操作符用于合并两个或多个 SELECT 语句的结果集.例如,我有两个表,表1记录的是公司男员工的数据,包括年龄.姓名.职位.表2记录的是公司女员工的数据,包括姓名.家庭住址.手机号等 ...
- 探索未知种族之osg类生物---渲染遍历之裁剪二
前言 上一节我们大致上过了一遍sceneView::cull()函数,通过研究,我们发现上图中的这一部分的代码才是整个cull过程的核心部分.所以今天我们来仔细的研究一下这一部分. sceneView ...