Java在windows环境中进行目录切换

本文介绍如何使用Java的Runtime类来执行DOS命令及调用可执行程序的方法。通过创建临时批处理文件,实现复杂命令序列的执行,并展示了如何读取执行过程中的输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java通过Runtime类可以调用环境中的可执行程序。

 

1、执行DOS命令

  exec("cmd.exe /c dir");   其中参数“/c”表示命令执行后立即关闭窗口

 

2、调用可执行命令

  exec("cmd.exe /c test.bat");  

  exec(" c:\\Program Files\\Microsoft Office\\office\\winword.exe .\\a.doc");

执行切换目录操作不能如此进行

  exec("cmd.exe /c cd d:\\"); 

  exec("cmd.exe /c dir"); 

 

经过网上查询,可将命令写进文件(exec.bat)保存在文件系统中后,再执行exec.bat。

 

代码如下:

 

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

public class Test {
	
	public static void main(String args[]) {
		Runtime r = Runtime.getRuntime();
		
		try {
			Test t = new Test();
			String userdir = System.getProperty("user.dir");//获取当前工作目录
			
			//开始生成脚本文件
			File f = new File(userdir+"\\exec.bat");
			FileOutputStream fos = new FileOutputStream(f);
			
			fos.write("c: \n".getBytes());
			fos.write("javac *.java \n".getBytes());
			fos.write("java HelloWorld badfish \n".getBytes());
			
			fos.flush();
			fos.close();
			
			//执行脚本文件
			t.exec(r,userdir+"\\exec.bat");
			
			//删除脚本文件
			f.delete();
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("Error executing notepad.");
		}
		
	}
	
	//执行命令同时打印屏幕信息
	public void exec(Runtime r , String arg) throws Exception{
		Process p = null;
		
		p = r.exec(arg);
		
		InputStream is = p.getInputStream();
		String s = null;
		LineNumberReader lnr = new LineNumberReader(new InputStreamReader(is));
		while( (s = lnr.readLine()) != null ){
			System.out.println(s);
		}
		
		System.out.println("~~~");
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值