How to execute a Java program from C#?

前端 未结 7 2067
遥遥无期
遥遥无期 2020-11-30 01:24

Wondering if anyone knows a nice way to execute a Java command-line program from C# code at run-time ?

Is it the same as executing native .EXE files ?

Wi

相关标签:
7条回答
  • 2020-11-30 01:44
    var processInfo = new ProcessStartInfo("java.exe", "-jar app.jar")
                          {
                              CreateNoWindow = true,
                              UseShellExecute = false
                          };
    Process proc;
    
    if ((proc = Process.Start(processInfo)) == null)
    {
        throw new InvalidOperationException("??");
    }
    
    proc.WaitForExit();
    int exitCode = proc.ExitCode;
    proc.Close();
    
    0 讨论(0)
  • 2020-11-30 01:51

    I added a couple of lines to the above solution. I wanted to call a Web Service from a Silverlight app that process some files using java on the server. The above solution is helpful but I modified a little bit so that it works since calling via a web service is a little bit trickier. Now you have the right tool for the job, C# when appropriate, Java when C# cannot solve the problem. It's always good to know more than just one way of doing things. Now my Web Service created in .Net can talk to Java.

    private void Merge(string strPath)
    {
      var processInfo = new ProcessStartInfo("C:\\Program Files\\Java\\jdk1.6.0_24\\binjava.exe", "-jar app.jar")
      {
         CreateNoWindow = true,
         UseShellExecute = false
      };
    
      processInfo.WorkingDirectory = strPath; // this is where your jar file is.
      Process proc;
    
      if ((proc = Process.Start(processInfo)) == null)
      {
        throw new InvalidOperationException("??");
      }
    
      proc.WaitForExit();
      int exitCode = proc.ExitCode;
      proc.Close();
    }
    
    0 讨论(0)
  • 2020-11-30 01:52

    Will it run synchronously or asynchronously

    It will run asynchronously if you have enough cores, otherwise it run independently, but your thread will have to context switch so the other program will run. Either way its not something you should need to worry about.

    0 讨论(0)
  • 2020-11-30 01:58

    It's the same as executing native .EXE files, only that the executable you will have to execute is the JVM itself (java.exe).

    So, inside your C# code call:

    java.exe -jar nameofyourjavaprogram.jar

    And you should be fine.

    If you don't have your java program on a JAR library, just make the JVM launch with all the parameters you need.

    0 讨论(0)
  • 2020-11-30 02:00

    If you need finer control than launching an external program, then consider IKVM - http://www.ikvm.net/ - which provides a way to run Java programs inside a .NET world.

    0 讨论(0)
  • 2020-11-30 02:05

    Maybe it would run faster if you use jni4net - C#/Java bridge

    0 讨论(0)
提交回复
热议问题