开发者

Is there a way to use java to execute a series of command line

I'm looking for a way 开发者_JAVA百科to compile visual studio c++ project in java. I know it's a bit strange to do it this way. but I'm doing a evolutionary algorithms. So Java is creating c++ code and compile it in Java not c++. I just need to automate it, so I don't have to copy the c++ code and paste it in .NET and click compile it.

So I'm looking for a way to execute series of command lines and display the result in eclipse console. Can I do that?

First I need to setup Visual Studio environment, so I need to run this batch first C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat and then change directory to the c++ project and compile the project by using "cl.exe" and then "link.exe". They need to be executed in a specific order.


Create a batch file and run it by using ProcessBuilder.

   import java.io.*;
   import java.util.*;

   public class DoProcessBuilder {
     public static void main(String args[]) throws IOException {

       if (args.length <= 0) {
         System.err.println("Need command to run");
         System.exit(-1);
       }

       Process process = new ProcessBuilder(args).start();
       InputStream is = process.getInputStream();
       InputStreamReader isr = new InputStreamReader(is);
       BufferedReader br = new BufferedReader(isr);
       String line;

       System.out.printf("Output of running %s is:", 
          Arrays.toString(args));

       while ((line = br.readLine()) != null) {
         System.out.println(line);
       }

     }
    } 


One of the easy way is as follows:

String[] cmd = new String[] { "yourcommand.exe", "argument1", "argument2", ... };
Process p = Runtime.exec(cmd);

You can also find other variation here, (eg by specifying environment and working directory too

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜