如何通过设置变量从Java执行命令行

时间:2014-04-10 08:27:40

标签: java windows command-line

try {
            String command = "java -Xms64m -Xmx512m -cp %mypath% com.app.GenericAxlTool -i " + ip + " -v 6.0 -a " + axlVer + " -d " + dbVer + " -u " + userName + " -p " + password + " -c sqlselect -f " + queryFile;
            String[] envArr = {pathCmd};
            System.out.println("Command is: " + command);
            ProcessBuilder pb = new ProcessBuilder(command);
            Map<String, String> env = pb.environment();
            env.put("mypath", ".;lib/gatui.jar;lib/gat.jar;lib/swing-layout-1.0.jar;lib/smtp.jar;lib/AbsoluteLayout.jar;lib/axis.jar;lib/commons-discovery-0.2.jar;lib/jaxm-runtime.jar;lib/jaxrpc.jar;lib/saaj-api.jar;lib/saaj-impl.jar;lib/activation.jar;lib/JSAP-2.1.jar;lib/SNMP4J.jar;lib/mailapi.jar;lib/jtapi.jar;lib/remotehands.jar;lib/conftransfer.jar;lib/jtapi.jar;;lib/devicedashboard.jar;lib/pcdb.jar;lib/lic.jar;lib/poi-3.8-20120326.jar");
            pb.directory(new File(curDir));
            Process p = pb.start();
            //Runtime runtime = Runtime.getRuntime();
            //Process p = runtime.exec(command, envArr, new File(curDir));
            InputStream is = p.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line;

            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
            p.waitFor();
            System.out.println("Done with: " + queryFile);
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        } finally {
            return false;
        }

上面的代码导致IOException,其次,我也没有得到流的任何输出。这是文件夹结构。

MainDir 
|
--lib
--src
   |
   --com.query.Exec
      |
      javafile.java

1 个答案:

答案 0 :(得分:0)

我不知道你要对你的代码做什么,但是为了执行命令行,你可以简单地使用
Runtime.getRuntime().exec(command)
其中command是表示您要运行的命令的字符串。