Friday, May 16, 2008

Taking input into batch file(sh file) from Java code

Most of the time when we start server, we write lot of code to optimize the condition. Most of those things are tough to write in Java but easy for batch file or sh file to work on. Like, go into a folder, set JAVA_HOME, setting some heap size and then fire the server. Things are not always start forward, sometime we need to pass some message or some path or some value from Java code to batch file.

Here I tried to write one. Say my JAVA_HOME is dynamic and on some condition I decide what's going to be JAVA_HOME and further on that what java and javac going to run(means setting path).

import java.io.*;
public class batchCheck {
public static void main(String[] args) {
//All JavaHomes
String javaHome[] = {"E:\\Program Files\\Java\\j2sdk1.4.2_05", "E:\\Program Files\\Java\\jdk1.6.0"};
String path;
String line = "";
String pathFile = "E:\\Program Files\\Java\\jdk1.6.0\\bin\\JavaOutput";
String whichJDK = "";
String decisionMaker = "142";
if (decisionMaker.equals("142")) {
whichJDK = javaHome[0];
} else {
whichJDK = javaHome[1];
}
try {
path = whichJDK + "\\bin";
String cmds[] = {"check.bat", pathFile, whichJDK, path};
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(cmds);
proc.getOutputStream().close();
InputStream inputstream = proc.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
while ((line = bufferedreader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Now, you can see my check.bat file:

cd %1
DEL HelloWorld.class
set PATH=%3
set JAVA_HOME=%2
echo %JAVA_HOME%
javac HelloWorld.java
java HelloWorld
exit

So, see how we can access the values from java file into batch file from %1, %2, %3 ... ($1,$2... in sh). Simply I moved on to the path where HelloWorld.java resides. I have deleted the old class file and the set the path, set the JAVA_HOME, compiled with javac of new JAVA_HOME and ran the code + exit :D.

Lot many things have been done from a very simple code.

1 comment:

Anonymous said...

This is great info to know.