Execute command using Java on Windows - java

I want to execute a command mspview -r "C:\\Users\\SS\\Desktop\\phantomjs-1.9.2-windows\\image.tif". How can I do it via Java code? I am trying to do this with a batch file. The same command when I run with the help of RUN. I am getting correct output. I have executed a .exe program with the help of a batch file with the following code C:\Users\SS\Desktop\phantomjs-1.9.2-windows\phantomjs.exe.

You're basically asking how to run shell commands in java, right?
Runtime.getRuntime().exec("whatever system call you want");

You need to use ProcessBuilder
Process process = new ProcessBuilder(
"C:\\PathToExe\\exe.exe","param1","param2").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);
}
code that is already found on stackoverflow
Execute external program in java

Related

running a shell script with user interaction from java

I'm trying to use a shell script in a java file.
The script runs then prints out the content of a file, and asks the user if its ok to continue
I can start the script off with this and see some output:
try {
process = processBuilder.start();
process.getOutputStream();
process.getInputStream();
process.getErrorStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String output_line = "";
while ((output_line = reader.readLine()) != null) {
System.out.println(output_line);
}
but I think when the file is closed it drops out of the while loop.
I was hoping to see "OK to proceed?" but it's just getting stuck on the last line of the file.
is there a way to keep reading from the command line until the script ends?

execute pig command in Java program

I used to write PHP code to execute pig command, it worked well,
Now I switch to Java but seems it won't work, here is my code:
String pigCommand = "pig -x local -p ouput=/tmp my_pig_script.pig";
Runtime r = Runtime.getRuntime();
Process p;
int exitVal;
try {
p = r.exec(pigCommand);
exitVal = p.waitFor();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
System.out.println("exitVal: " + exitVal);
System.out.println("Done");
If I run the that pig command in console directly, it works, if I replace
that Pig command with other shell command say 'ping www.yahoo.com', and run the
java Program, it works too. So what might be the problem? thanks
You should use PigServer to execute pig scripts from java programs. It is more foolproof and more portable.
Also see this answer: https://stackoverflow.com/a/11299259/373151

How to edit file on console from Java?

I'm trying to edit a file from CLI. I'm executing the nano command (I know that command will always be available); when I execute it, I can see nano's output but I cannot interact with it. How can I pass user input to the command? Do you have a better idea to easily edit a file from within my Java app?
This is my code:
String command = "nano /tmp/163377867.txt ";
try {
Process process = Runtime.getRuntime().exec(command);
InputStream inputStream = process.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
The problem with Java's Runtime.exec is that it connects stdin and stdout to "pipes," while many console programs need a TTY device.
One way to solve this problem is to make the Java program's controlling terminal available to the program you execute:
Process proc = Runtime.getRuntime().exec(new String[]{
"sh", "-c", command+" </dev/tty >/dev/tty"});
proc.waitFor(); // wait for user to finish editing the file

Running Python scripts in Java

I'm trying to run a python script during the execution of my java code, because it will depend on the output received from the python script. So far I've tried using jythonc, unfortunately to no success, and now im trying to use the java Runtime and java Process to execute the python script.
Now I've run into a problem when trying to call the python script. I feel as though it doesn't even call the script because it takes less than a couple seconds to get to the next page....
Could the problem be how I am calling the python script?? I am trying to run this through a web application...
Here is some of my code:
String run = "cmd /c python duplicatetestingoriginal.py" ;
boolean isCreated = fwr.writeFile(BugFile, GD, 500, true, 5, "LET");
if(isCreated){
try{
r = Runtime.getRuntime();
p = r.exec(run);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line = "";
while ((line = stdInput.readLine()) != null) {
System.out.println(line);
}
while ((line = stdError.readLine()) != null) {
errorW.write(line);
}
int exitVal = p.waitFor();
arrayList = fwr.readResults();
}catch(Exception e){
}
}
else{
// troubleshoot....
}
Instead of String for the command, split it to chunks and make a String[]. No need to state cmd /c, I think.
This is a sample code from my application:
//Running on windows
command = new String[4];
command[0]=directory.getCanonicalPath()+"/data/ExtenalApp.exe"; //extenal commandline app, not placed in path, but in subfolder
command[1]=directory.getCanonicalPath()+"/data/SomeFile.txt"; //file needed for the external app, sent as an argument
command[2]=arg1; //argument for the app
command[3]=arg2; //argument for the app
//Running on Mac
command = new String[6];
command[0]="python";
command[1]=directory.getCanonicalPath()+"/data/wp.py"; //path to the script
command[2]="-F"; //argument/Flag/option
command[3]="--dir="+path; //argument/option
command[4]="--filename="+filename; //argument/option
command[5]=argument; //argument/option
Process process = Runtime.getRuntime().exec(command);
process.waitFor();
process.destroy();
I don't handle the Input/Output streams because the script/app doesn't require input, and outputs only when finished, nothing important. Which might not be the case for you.

Running Shell Script at the command line

I am running a Shell script using cygwin.
Process p;
InputStream in;
BufferedReader br;
String line;
String cmd;
cmd = "D:/cygwin/bin/bash -c '/bin/test/app.sh" +three_ltr_id+""+mon_code+""+year_code+""+part_no+""+version_no+" '";
System.out.println("EXECUTING: " + cmd);
p = Runtime.getRuntime().exec(cmd);
in = p.getInputStream();
p.waitFor();
br = new BufferedReader(new InputStreamReader(in));
System.out.println("OUT:");
while ((line = br.readLine()) != null) {
System.out.println(line);
System.out.println("SCRIPT EXECUTED PROPERLY");
This is showing EXECUTING and the commands that I passed to script.
If I go inside D:/cygwin/bin/test folder and run the same command it works.
When I run the same command at the command line it won't work.
You need to start reading the input from p.getInputStream() immediately, and keep reading it until there is no more. On Windows, there is little or no buffer in the pipe, and the process will hang once it is filled.
Same is true for the error stream. You could launch threads to read both streams, or there's an option in the way you launch processes to combine regular output and errors, and you can just read them from there.

Categories

Resources