我需要在cmd提示符中执行以下更改目录命令,但是使用java来执行它们。dir命令工作正常,但cd命令不起作用。我必须在一个cmd窗口中执行它们。
cd inputDir
dir
cd outputDirinputDir和outputDir是窗口中的目录。
Java片段:
ArrayList<String> dosCommands = new ArrayList<String>();
Process p;
for (int i=0;i< dosCommands.size();i++){
p=Runtime.getRuntime().exec("cmd.exe /c "+dosCommands.get(i));
p.waitFor();
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=reader.readLine();
while(line!=null)
{
System.out.println(line);
line=reader.readLine();
}
}更新
将参数更改为cmd.exe /k而不是/c
p=Runtime.getRuntime().exec("cmd.exe /k "+dosCommands.get(i)); 我不得不移除
p.waitFor(); 方法,因为我被塞进去了。这样做,我知道我确实被塞进了
line.reader.readLine(); 发布于 2015-06-29 19:24:27
使用
cmd.exe /K不
cmd.exe /c您可以找到更多关于cmd参数的信息。
使用/c,cmd完成并退出。使用/k,它不会退出。
__UPDATE__
我的意思是:
cd inputDir
dir
cd outputDir
exit请注意最后一行。
__UPDATE 2__
请在代码中使用类似的内容,根据正在运行的过程,找出当前工作目录是什么:
public class JavaApplication1 {
public static void main(String[] args) {
System.out.println("Working Directory = " +
System.getProperty("user.dir"));
}
}在此之后,让我们确保您想要cd的文件夹存在于该文件夹中。
发布于 2015-06-29 19:49:43
尝试这个实验:打开一个命令窗口(使用鼠标和/或键盘,而不是使用代码)。现在切换到另一个目录,使用类似于cd \或cd C:\Windows的命令。
然后打开第二个命令窗口。它的当前目录是什么?它还记得你在第一个命令窗口做了什么吗?
它没有这样做,因为每次运行cmd.exe时,都会启动一个具有自己当前目录状态的新进程。
在您的代码中,您将在for-循环的每次迭代中执行一个新的cmd.exe进程。每次启动新的cmd.exe时,它都不知道当前目录在其他cmd.exe实例中可能是什么。
可以设置进程执行的当前目录:
String inputDir = "C:\\Users\\eleite\\Workspace\\RunCmd\\Petrel_Logs";
p = Runtime.getRuntime().exec("cmd.exe /c " + dosCommands.get(i),
null, inputDir); 发布于 2015-06-30 14:46:46
如果你想
然后试试下面的代码
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/k");
pb.redirectOutput(Redirect.INHERIT);//redirect process output to System.out
pb.redirectError(Redirect.INHERIT);//redirect process output to System.err
Process p = pb.start();
try(PrintWriter pw = new PrintWriter(new OutputStreamWriter(p.getOutputStream()), true)){
pw.println("dir");//execute command 1, for instance "dir"
pw.println("ver");//execute command 2, for instance "ver"
//... rest of commands
pw.println("exit");//when last command finished, exit console
}
p.waitFor();//this will make main thread wait till process (console) will finish (will be closed)
//here we place rest of code which should be executed after console after console process will finish
System.out.println("---------------- after process ended ----------------");因此,如果您想要执行的命令列表,只需将它们放在这里:
try(PrintWriter pw = new PrintWriter(new OutputStreamWriter(p.getOutputStream()), true)){
//here and execute them like
for (String command : dosCommands){
pw.println(command);
}
pw.println("exit");//when last command finished, exit console
}https://stackoverflow.com/questions/31123859
复制相似问题