Tuesday, September 16, 2008

Execute Java jar file from .Net

Step1: Creating a Java Class

package ZAQ;

import javax.swing.JOptionPane;
public class Hello {
public static void main (String [] args) {
JOptionPane.showMessageDialog(null, "Hello World!");
}
}

Put this Class Inside ZAQ directory and set the class file name as Hello.java


Step2: Preparing of mainClass.txt file.
Write the following line in the file. Please remember to put a carriage return after the line.
Main-Class: ZAQ.Hello


Step3: Compile the Java Class and Build the jar file
Create class file for Hello.java and then build the jar file. Do the following commands
->Javac ZAQ/Hello.java
->jar cmf mainClass.txt ZAQ.jar ZAQ
->java –jar ZAQ.jar Hello
Now your jar is ready.


Step4: Create a batch file to be execute in .Net
Save a file with the following text:
java -jar D:\ZAQ.jar


Step5: .Net code is here.

int i = 0;
string sOut = ShellExec(@"d:\Comm.bat", "", "", out i);
Console.WriteLine(sOut);

And the function is here:

protected static String ShellExec(String cmd, String path, String parms, out int exit_code)
{
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(path + cmd, parms);
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;

System.Diagnostics.Process p = System.Diagnostics.Process.Start(psi);
string tool_output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
exit_code = p.ExitCode;
return tool_output;
}

No comments: