Program execution in java - java

I am trying to open an exe file, specificly the IndriRunQuery.exe which is one of the tools that offers the Lemur Indri package. When i use the command prompt i write the following command:
IndriRunQuery Queries.txt
With this, the editting of the queries that are included in Queries.txt (which is passed as a parameter in the above command) is starting.
Then after a descent amount of time has passed ,i write the following in order to save the results that are produced in a file named Results.txt:
IndriRunQuery Queries.txt >Results.txt
My problem is that every time that i want to edit a file which contains queries
i need to do the same steps. i have 20 different query files to edit. I am trying to find a way to do it by using a java program but i can not figure it out.
I have used these lines of code but it doesnot work at all.
Can anyone help me out with this?
ProcessBuilder builder = new ProcessBuilder("C:\\Program Files\\Indri\\Indri 5.8\\bin\\IndriRunQuery.exe",
"C:\\Users\\Πετρής\\Desktop\\TitlesRel.txt");
builder.start();
ProcessBuilder builder2 = new ProcessBuilder("C:\\Program Files\\Indri\\Indri 5.8\\bin\\IndriRunQuery.exe",
"C:\\Users\\Πετρής\\Desktop\\TitlesRel.txt",">C:\\Users\\Πετρής\\Desktop\\resultsexample3.txt");
builder2.start();

The correct syntax is as below:
// Create ProcessBuilder.
ProcessBuilder p = new ProcessBuilder();
// Use command "notepad.exe" and open the file.
p.command("notepad.exe", "C:\\file.txt");
p.start();
Or
Process p = Runtime.getRuntime().exec("cmd /c start " + file.getAbsolutePath());

Related

How to run commands you can run on terminal in Java

So guys I want to execute a command that you can execute on the cmd in my Java program. After doing some study, I thought i found a way to do this. However, my code doesn't work.
My code is
import java.io.*;
public class CmdTest {
public static void main(String[] args) throws Exception {
String[] command = {"ag","startTimes conf.js >> pro.txt"};
ProcessBuilder builder = new ProcessBuilder(command);
builder.directory(new File("./test-java/"));
Process p = builder.start();
}
}
The program executes but produces no output. I tried using other commands like "ls -a", but still no output.
Can someone please help me debug this or suggest a better way of doing this? Thank you
Edit 1: I am executing this on a Mac. If that is necessary for debugging
Edit 2: The usual ls and other commands are working with the solutions that you guys have provided. I however want to use the ag (the_silver_searcher) command in the Java program. When i try that, i get the following error -
Exception in thread "main" java.io.IOException: Cannot run program "ag startTimes conf.js >> pro.txt": error=2, No such file or directory
The existing answers give you the information on how to solve your problem in code, but they don't give a reason why your code is not working.
When you execute a program on a shell, there's significant processing done by the shell, before the program is ever executed. Your command line
String[] command = {"ag","startTimes conf.js >> pro.txt"};
ProcessBuilder builder = new ProcessBuilder(command);
assumes that the command ag is run with the single argument startTimes conf.js >> pro.txt - most likely not what you want to do. Let's go one step further: What if you wrote
String[] command = {"ag","startTimes", "conf.js", ">>", "pro.txt"};
ProcessBuilder builder = new ProcessBuilder(command);
?
This would assume that the ag command knows about the >> parameter to redirect its output - and here is where the shell comes into play: The >> operator is an instruction to the shell, telling it what to do with the output from stdout of the process. The process ag, when started by the shell, never has an idea of this redirection and has no clue about >> and the target file name at all.
With this information, just use the code samples from any of the other answers. I won't copy them into mine for proper attribution.
While there is ProcessBuilder, I've always used Runtime.getRuntime().exec("cmd");
Process Runtime.exec(String)
It returns a Process which you can get the input and output streams of
Even if you stay with the ProcessBuilder, you should still have access to the Process.get<Input/Output/Error>Stream()
You need to read the output of the process by opening an input stream from the process:
try (BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())) {
System.out.println(reader.readLine()); // process the output stream somehow
}
Additionally you might the read the error stream ( p.getErrorStream()), which I often have done in a separate stream, in Java 8 you can use redirectErrorStream(true) on the ProcessBuilder to automatically add the error stream to the input stream. Of course you can't distinquish anymore from which stream the input comes, but it makes reading easier. If you don't read the input or error stream and the process's buffer becomes full the processes tend to pause until there is enough room in the buffer again.
You can also add
builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
before the start method which redirects the output to the console.
//"ls" command runs under the "sh" on linux(cmd.exe on windows), so first arg is "sh"
//second arg "-c" tells "sh" which exact command should be executed
//"ls" is actual command
//"startTimes" as I understand is a file or directory, it is arg for "ls" command
//"conf.js" is second arg for "ls" command
new ProcessBuilder("sh", "-c", "ls", "startTimes", "conf.js")
//set working dir for "sh" process"
.directory(new File("./test-java/"))
//output will be written to "pro.txt" in working dir of "sh" process
.redirectOutput(new File("./test-java/pro.txt"))
.start();

How to pass file as an argument to Python process invoked by Java

I am running Java program to call Python process using process builder as shown below,
processBuilder = new ProcessBuilder(
Arrays.asList(
"/usr/bin/python",
"/opt/gui/oc_db5.py",
"-c",
"/opt/gui/test.json")
);
processBuilder.directory(new File("/opt/gui"));
processBuilder.start();
Location of python program is under /opt/gui directory and there is one test.json file also needs to be passed as parameter, with "-c" option, However what i am seeing is that system is appending location of java program with path of JSON file and then pick the .JSON file causing issue for Python code.
What actually python program is getting is /opt/java//opt/gui/test.json. I tried ../../ as well but it didn't work with test.json file.
Is there a way i can specify .JSON file as an argument to python program?
This seemed to work for me. I mean, it fixed the directory problem.
try {
int exitCode = Runtime.getRuntime().exec("python /opt/gui/oc_db5.py -c /opt/gui/test.json", null, new File("/")).waitFor(); // run program and get exit code
} catch(Exception e) { // is there an error?
e.printStackTrace(); // print error
}

Runtime.exec(String) limiting String

I'm trying to use the Java function Runetime.exec(String) to run a program in the startup folder of a windows 7 computer like so:
Runtime.getRuntime().exec(runner.getPath() + "\\run.bat");
And when I run this I get an error saying the command cannot be run:
Exception in thread "main" java.io.IOException: Cannot run program ""C:\Users\ly
ndsey\AppData\Roaming\Microsoft\Windows\Start": CreateProcess error=2, The syste
m cannot find the file specified
As you can see, the file name is cut off at the "\Windows\Start" when it should continue to "\Windows\Startup\run.bat".. Is there an alternative I can use?
Considering runner as a File instance, this should work.
Desktop.getDesktop().open(new File(runner, "run.bat"));
It uses Desktop class instead of Runtime, so you don't have to convert your File (runner) to its String representation (which is error prone). Runner is now used 'as is' as the parent directory of the "run.bat" you want to execute.
Other advantage of Desktop class : you can now open any file you want.
As an alternative you can use ProcessBuilder. I feel ProcessBuilder is more safe than Runtime.getRuntime().exec http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html
String[] command = {"CMD", "/C", "dir"};
ProcessBuilder pb = new ProcessBuilder( command );
//set up your work directory if needed
pb.directory(new File("c:\\path"));
Process process = pb.start();
as i can see from the error you give, and i hope it's a copy past, you string runner.getPath() for some reason start and end with "\"" which make the whole path invalid. check that and remove it if needed
if you have the file already and you just need it's path you can use
runner.getAbsolutePath()
also, if runner is a file, getPath will give you the file path including the path, so your code will surely won't work. instead use:
String path = runner.getPath();
path = path.substring(0, path.lastIndexOf("\\")) + "\\run.bat";
Runtime.getRuntime().exec(path);
You should avoid the exec(String) method, which attempts to parse the entire string into command + arguments. The safe option is exec(String[]), which presupposes the first array element is the command and the rest are arguments.
So, writing
Runtime.getRuntime.exec(new String[] { yourCommandString })
is a surefire way of getting the right message across.

Calling jar in my java code

I want to use a jar file Command.jar in my java code. When I run Command.jar from command line
like this java -jar Command.jar "Param1" it works well. But when I try to run it in my java code using either Process builder or Runtime.getRuntime().exec it does not work.
I tried this -
List <String> command = new ArrayList<String>();
command.add("java -jar");
command.add("Command.jar");
command.add("Param1");
ProcessBuilder builder = new ProcessBuilder(command);
try {
Process process = builder.start();
} catch (IOException e) {
}
It does not work. I also tried this:
Runtime.getRuntime().exec("java -jar Command.jar Param1");
But no luck. Please tell me where I am doing wrong
This is incorrect:
command.add("java -jar");
It should be
command.add("java");
command.add("-jar");
But there may be other problems as well. For instance java may not be accessible via the search path given by the PATH environment variable. Or Command.jar may not be in the current directory.
You need to see what (if anything) is being written by the java command to its standard output and/or standard error streams.
it does not work
does not tell us how to help you. You'll need to give us an error message or undesired result. Use System.out.println's to help you debug and narrow the problem.
From what I can guess from personal experience and other problems is that you probably ran some cd "Directory\With\Path\To\Jar" commands in command prompt when you were running it manually. You'll need to do the same for Runtime.getRuntime().exec or put the jar in the location that exec will default to in your program.
Did you try using ProcessBuilder(java.lang.ProcessBuilder)? Syntax is as follows -
ProcessBuilder pb = new ProcessBuilder("java", "-jar", "absolute path upto jar");
Process p = pb.start();
You can redirent input/output/error to/from files as follows
File commands = new File("absolute path to inputs file");
File dirOut = new File("absolute path to outputs file");
File dirErr = new File("absolute path to error file");
dirProcess.redirectInput(commands);
dirProcess.redirectOutput(dirOut);
dirProcess.redirectError(dirErr);
I have tried it and it work! Let us know any errors or exceptions you are getting.

Save output of external program call in textfile in java

I am using Windows!
I want to call a small .exe application from my java command line which is called "saucy.exe". It needs an input file "input.saucy". Both are stored in the correct directory.
When I use the command
Process p = Runtime.getRuntime().exec("saucy input.saucy");
everything works fine and I get an output on the console.
However, when I try to write the output in a file
Process p = Runtime.getRuntime().exec("saucy input.saucy > output.saucy");
nothing happens.
I already found the advice in http://www.ensta-paristech.fr/~diam/java/online/io/javazine.html and tried to tokenize the command manually:
String[] cmd = {"saucy", "input.saucy > output.saucy"};
Process p = Runtime.getRuntime().exec(cmd);
It is still not working. Any advice? It is no option for me to write the output to a file with java code, because its too slow.
Again: I am using Windows (I stress that because I read several hints for Linux systems).
> is a shell command, but you are not using one. try
String[] cmd = { "cmd", "/C", "saucy input.saucy > output.saucy" };
If you are on Java 7 you can use the new ProcessBuilder.redirectOutput mechanism:
ProcessBuilder pb = new ProcessBuilder("saucy", "input.saucy");
// send standard output to a file
pb.redirectOutput(new File("output.saucy"));
// merge standard error with standard output
pb.redirectErrorStream(true);
Process p = pb.start();
Use the getInputStream(), getOutputStream() and getErrorStream() to retrieve the output (or send input).
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Process.html

Categories

Resources