您的位置:首页 > 编程语言 > Java开发

Java调用windows Dos命令的用法

2016-12-05 16:30 441 查看
windows的dos命令给我们调用windows的服务提供了非常方便的通道,但是在Java开发中涉及到一些文件的操作的时候,我们可能需要调windows内置的命令来获取文件的相关信息,并进行相应的处理,下面给出一个调用windows dos命令的基础案例

package com.zhiwei.basic;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

/**java调用windows本地命令*/
public class DosOperation {

public static void main(String[] args) {

InputStream is=null;
BufferedInputStream bis=null;
Process process=null;

/**命令参数*/
String[] cmd=new String[]{"cmd.exe","/c","dir"};

try{

process=Runtime.getRuntime().exec(cmd);
is=process.getInputStream();
bis=new BufferedInputStream(is);
byte[] buf=new byte[1024];
while((bis.read(buf))!=-1){
System.out.println(new String(buf,"GBK"));
}

int exitValue=process.waitFor();
System.out.println("返回值:"+exitValue);

}catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(bis!=null){
bis.close();
}
if(process!=null){
process.getOutputStream().close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}


结果:

驱动器 E 中的卷是 Entainment

卷的序列号是 000B-75D9

E:\JavaProject\JavaPro 的目录

2016/11/28 11:07
.

2016/11/28 11:07 ..

2016/11/28 10:36 1,759 .classpath

2016/05/25 14:22 383 .project

2016/09/26 23:45 .settings

2016/12/05 10:57 bin

2016/11/24 11:42 lib

2016/11/28 12:10 src

2 个文件 2,142 字节

6 个目录 145,481,375,744 可用字节

返回值:0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  windows dos java