我正在尝试通过java运行cmd命令。命令如'资源管理器','记事本'正在运行,但命令如“' dir' '路径'没有工作它抛出异常,输出说: -
执行命令java.io.IOException时出现问题:无法运行程序" path":CreateProcess error = 2,系统找不到指定的文件
boolean exc(String command){
Process p;String pingResult="";
try{
p=Runtime.getRuntime().exec(command);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
pingResult += inputLine;
}
in.close();
return true;
}catch(Exception e){
System.out.println("Problem in Executing Command "+e.toString());
return false;
}
}
看看我的代码中是否有任何问题。
答案 0 :(得分:0)
用于列出指定路径的目录的程序
你可以使用下面的代码,你应该得到你想要的欲望
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package checkapplicationisopen;
import java.io.*;
public class TestExec {
public static void main(String[] args) {
TestExec testExec=new TestExec();
System.out.println(testExec.getDirectoryList("C:\\Documents"));
}
/**
*
* @param path directory path which you want to retrieve the directory and files
* @return the list of directories and Files with the size
*
*/
public String getDirectoryList(String path)
{
String dirList="";
try {
Process p = Runtime.getRuntime().exec("cmd /C dir "+path);
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
dirList+=line;
}
} catch (IOException e) {
e.printStackTrace();
}
return dirList;
}
}