简体   繁体   English

更改工作目录,然后在Java中运行带有参数的批处理文件

[英]change working directory then run a batch file with parameters in java

I need to change the working directory first. 我需要先更改工作目录。 Then run my batch file with some parameters located in .txt file. 然后使用位于.txt文件中的某些参数运行我的批处理文件。 I searched to open a batch file, though it works I am unable to change working directory and then run it and to pass parameters too. 我搜索打开了一个批处理文件,尽管它可以工作,但是我无法更改工作目录,然后再运行它并传递参数。

Java Snippet: Java代码段:

final String dosCommand = "cmd /c start cmd.exe /K";
      final String location = "\"C:/Program Files/.../abc.bat";
      final String trail = "d:\\xyz.txt";
      try {
         final Process process = Runtime.getRuntime().exec(
            dosCommand + " " + location + " " + "pro_wait" + " " + trail);
         final InputStream in = process.getInputStream();
         int ch;
         while((ch = in.read()) != -1) {
            System.out.print((char)ch);
         }
      } catch (IOException e) {
         e.printStackTrace();
      }

On command prompt I am executing command as, 在命令提示符下,我正在执行命令,

D:\>"C:\Program Files\...\abc.bat" pro_wait d:\xyz.txt 

I am unable to execute complete command from JAVA. 我无法从JAVA执行完整的命令。 Please help. 请帮忙。 Thanks in advance to all! 在此先感谢所有人!

You should remove the "start" from the dosCommand and ensure the quotes around the batch file are complete. 您应该从dosCommand中删除“ start”,并确保批处理文件周围的引号是完整的。 You can then specify the working directory together with the command in the exec method: 然后,您可以在exec方法中指定工作目录以及命令:

    final String dosCommand = "cmd /c cmd.exe /K";
    final String location = "\"C:/Program Files/.../abc.bat\"";
    final String trail = "d:\\xyz.txt";
    try {
        final Process process = Runtime.getRuntime().exec(
                dosCommand + " " + location + " " + "pro_wait" + " " + trail,
                null, new File("D:\\"));
        final InputStream in = process.getInputStream();
        int ch;
        while ((ch = in.read()) != -1) {
            System.out.print((char) ch);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM