java执行命令

我之前写过一个使用手机远程控制电脑关机的程序,主要用到的就是使用java执行windows的关机命令"shutdown -r -t " + time

主要代码:

		CommandData cd = CommandData.valueOf(commandData);
		Runtime rt = Runtime.getRuntime();
		try {
			switch (cd) {
			case REBOOT://重启
				rt.exec("shutdown -r -t " + time);
				break;
			case SHUTDOWN://关机
				rt.exec("shutdown -s -t " + time);
				break;
			case LOGOFF://注销
				rt.exec("shutdown -l");
				break;
			case DORMANT://休眠
				this.OpenHibernate();
				rt.exec("shutdown -h");
				break;
			case LOCK://锁定
				rt.exec("rundll32.exe user32.dll,LockWorkStation");
				break;
			case CANCEL://取消
				rt.exec("shutdown -a"); 
				break;
			default:
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
当然这里只是简单的应用


现在我需要执行一个bat文件,还是以这种方式去执行,可以执行,但是会有些问题

在bat文件中有这样一句代码: @call ".\adminserver.cmd" start_ui_client

这句代码的意思是去调用上层文件夹的adminserver.cmd文件

这时候会出现找不到该文件的错误


这是为什么呢?


问题出在RunTime.exec(command)这个方法上.


其实所有的exec方法都是调用的public Processexec(String[] cmdarray, String[] envp,File dir)throwsIOException

dir:指定了新子进程的工作目录。如果 dir 为 null,那么子进程会继承当前进程的当前工作目录。

这里dir就是null


解决方法就很明确了


上一段当时我写的代码:


String dir = "D:/kingdee/eas/admin/";//执行命令行工作目录
String paramFile = "C:/Users/Administrator/Desktop/importLicense.properties";//参数文件的全路径
String logFile = "C:/Users/Administrator/Desktop/importLicense.log";//日志文件的全路径
String automate = "automate.bat";//执行文件
String type = task.getTaskCommand();//执行命令
String licenseFilePath = "C:/Users/Administrator/Desktop/license/";//网络上下载的license文件存放路径
String link = "http://54.222.201.211:8088/eascloudsystem/license/licenseFileDownloadAction?licenseId=";//下载license文件的链接

String[] command = {"cmd.exe","/c",automate,type,paramFile,logFile};//执行时就执行这个数组里的东西
/**
	 * 执行命令
	 * @param dir		执行命令行工作目录
	 * @param command	执行时就执行这个数组里的东西
	 */
	private void executeCommand(String dir,String[] command){
		Runtime rt = Runtime.getRuntime();
		BufferedReader input = null;
		try {
			Process process = rt.exec(command,null,new File(dir));
			input = new BufferedReader(new InputStreamReader(process.getInputStream(), "utf-8"));  
			  
		    String line = null;  
		    while ((line = input.readLine()) != null) {
		    	System.out.println(line);
		    }  
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			if(input!=null)
				try {
					input.close();
					
					//命令执行完毕后就检查任务是否执行成功
				} catch (IOException e) {
				}
		}
		


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值