When I try to execute an external program from java I use this code below :
Process p;
rn = Runtime.getRuntime();
String[] unzip = new String[2];
unzip[0]="unzip";
unzip[1]=archive ;
public void dezip() throws IOException{
p = rn.exec(unzip);
int ret = p.exitValue();
System.out.println("End of unzip method");
But my last System.out is never executed, as if we exit from unzip method.
The unzip() call does only the half of the work, only a part of my archive is unzipped.
When I use ps -x or htop from command line I see that unzip process is still here.
Help please.
You probably need to read the InputStream from the process. See the javadoc of Process
Which states:
Because some native platforms only provide limited buffer size for
standard input and output streams, failure to promptly write the input
stream or read the output stream of the subprocess may cause the
subprocess to block, and even deadlock.
Check if the unzip command is prompting for something, perhaps a warning if the file already exists and if you want to overwrite it.
Also, is that a backquote I see in the middle of a java program?
Make sure external program doesn't wait for user input
Check if the the executable path is quoted when launching on Windows systems to handle directories with spaces or special characters.
PS.
I was using the java.lang.Runtime class but found that the java.lang.ProcessBuilder class is far superior. You can specify current working directory, and most importantly the system environment.
Please try the following:
p = rn.exec(unzip);
p.waitFor()
I hope it will change something.
Related
In the project I am working on, I need to execute a script that I have in a resources folder -- in the class path. I am simply testing the final script functionality, since I am on Windows, I needed a way to output a file to STDIN so I created a simple cat.jar program to clone unixs cat command.
So when I do "java -jar cat.jar someFile.txt" it will output the file to stdout. I'm sure there are different ways of doing what I did.
Anyways,
I want to run that JAR from my main java program.
I am doing
Runtime.getRuntime().exec("java -jar C:/cat.jar C:/test.txt");
I've tried switching the forward slash to a backward slash and escaping it -- didn't work.
Nothing is getting sent to standard out.
Where as, if I run the cat jar on its own, I get the file directed to standard out.
What am I doing wrong here?
Is this enough information?
Use the Process instance returned by exec()
Process cat = Runtime.getRuntime().exec("java -jar C:/cat.jar C:/test.txt");
BufferedInputStream catOutput= new BufferedInputStream(cat.getInputStream());
int read = 0;
byte[] output = new byte[1024];
while ((read = catOutput.read(output)) != -1) {
System.out.println(output[read]);
}
References:
http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html
By default, the created subprocess does not have its own terminal or console. All its standard I/O (stdin, stdout, stderr) operations will be redirected to the parent process, where they can be accessed via the streams obtained using the methods getOutputStream(), getInputStream(), and getErrorStream().
http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html#getInputStream()
getInputStream() returns the input stream connected to the normal output of the subprocess.
I have sample java code like below.
String testEfdDirectoryPath="D:\\test";
String efdExecutable = "test.cmd";
File executableFile = new File(testEfdDirectoryPath, efdExecutable);
ProcessBuilder pb=new ProcessBuilder();
$$pb.command("cmd.exe","/C",executableFile.toString());$$
pb.directory(new File(testEfdDirectoryPath));
Process p=pb.start();
int code=p.waitFor();
System.out.print(code);
In test.cmd there is actually a call to another java application. Unless I change the $$ marked line to the following to redirect its output, the another java app cannot be launched.
pb.command("cmd.exe","/C",executableFile.toString(),">output.txt");
Do you guys have any ideas? Thanks in advance. :)
Does your child process produce a lot of output (more than a few kilobytes)? If that is the case, you need to read that output from the process. You should try:
start the process
close the stdin of the process, so pb.getOutputStream().close()
repeatedly read from pb.getInputStream() and the error stream
This may be possible in one thread, or in multiple threads. Anyway, you should just take the explanation above as a list of keywords and try to search for an example code snippet that you can trust, preferrably from an Open Source application that does such a thing successfully.
Maybe http://commons.apache.org/exec/ can help you.
Windows cannot execute scripts directly; when you double click on a .cmd file it actually opens the file in cmd.exe. So try cmd.exe E:\\test\\test.cmd.
I'm making an update function for my project, it's working great, until i want it to restart, basically I download the new file and replace it with the old one, and then i want to run it again, now for some reason it doesn't wna run, and i don't get any error...
Here is the complete update class:
http://dl.dropbox.com/u/38414202/Update.txt
Here is the method i'm using to run my .jar file:
String currDir = new File("(CoN).jar").getAbsolutePath();
Process runManager = Runtime.getRuntime().exec("java -jar " + currDir);
It's not clear to me, why do you need to run the jar with a call to exec() . Given that you need to run the code in the .jar file from a Java program, you could simply run the main() method as defined in the jar's manifest, and capture its output - wherever that is.
Using exec() is OK when you need to call a program from the underlying operating system, but there are easier ways to do this if both the caller and the callee are Java programs.
Now, if your jar is gonna change dynamically and you need to update your program according to a new jar, there are mechanisms for reloading its contents, for instance take a look ath this other post.
The JavaDocs for the Process class specifically point out that if you don't capture the output stream of the Process and promptly read it that the process could halt. If this is the case, then you wouldn't see the process that you started run.
I think you have to capture the stream like this :
BufferedReader stdInput = new BufferedReader(new InputStreamReader(runManager.getInputStream()),8*1024);
BufferedReader stdError = new BufferedReader(new InputStreamReader(runManager.getErrorStream()));
// read the output from the command
String s = null;
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
The exec function doesn't automatically lookup into the PATH to start a process, so you have to pass the complete path for the java binary.
You can do that by using the java.home system property, see this answer: ProcessBuilder - Start another process / JVM - HowTo?
No one here seemed to help me, so I went to ask my friend and I had it almost right. It abiously required the string to be an array.
solution:
String[] cmd = {"java", "-jar", currDir};
try {
Runtime.getRuntime().exec(cmd);
} catch (IOException e1) {
e1.printStackTrace();
}
I am looking for a help regarding a shell script to redirect the output of a command to a file. I have a C program that reads the input from a serial port and display. I want this data to be redirected to a file. I am executing this from a java program by calling
Runtime r = Runtime.getRuntime();
Process procObj = r.exec("sh " + scriptfile);
I have tried writing the script file as
./program >> file.txt
The file.txt is not getting updated. Here, the program doesn't end until the connection to the port is lost, in a sense it is infinitely running. So my program keeps looking for data on the port and display as and when it is there.
I just need to redirect the same output to a file that I would use as a log.
I looked at How to make shell output redirect (>) write while script is still running? but not helpful.
Kindly help..
How much output does program generate? Using standard IO redirection will add a 4KB buffer between stdout and file. This means your program must output more than 4KB of data before the OS starts to write to the file.
To fix this, add stdout.flush() to your program when a "work unit" is complete (maybe a line but might be more than one line).
Can you try ./program >> file.txt 2>>file.txt, or ./program 2>&1 >>file.txt?
just try this
List<String> cmd = new ArrayList<String>();
cmd.add("sh");
cmd.add("-c");
cmd.add("program 1> file.txt 2>&1");
ProcessBuilder pb = new ProcessBuilder(cmd);
Process p = pb.start();
If you use standard C calls for output (printf, puts etc.), your output may get buffered. On C89 and onwards, it depends on the buffering mode (unbuffered, fully buffered, line buffered) and on the size of the buffer, whether your output is buffered at all and when the buffer is flushed (see http://www.gnu.org/software/libc/manual/html_node/Buffering-Concepts.html and man setvbuf).
By default, output to a file is fully buffered on Linux. If you want the output to appear immediately in the output file, you may:
use fflush() after each output operation
use the system call write() (man 2 write)
switch off buffering: setvbuf(stdout, NULL, _IONBF, 0); (https://stackoverflow.com/a/7876756/601203)
This behaviour is not related on the fact the you start your C program in a Java program via a shell script. This behaviour depends on the standard C library that you have linked into your program.
I'm trying to run a program ignoring its output, but it seems to hangs when its output is large. My code is as follows:
Process p = Runtime.getRuntime().exec("program");
p.getOutputStream().write(input.getBytes());
p.getOutputStream().flush();
p.getOutputStream().close();
p.waitFor();
What is the best way to ignore the output?
I tried to redirect the output to /dev/null, but I got a Java IOException 'Broke pipe'.
Did you try:
Process p = Runtime.getRuntime().exec("program >/dev/null 2>&1");
?
I remember having to do something similar in Java before, but I may not have been calling the process the same way.
Edit: I just tested this code and it successfully completes.
class a
{
public static void main(String[] args) throws Exception
{
Process p = Runtime.getRuntime().exec("cat a.java >/dev/null 2>&1");
p.getOutputStream().write(123123);
p.getOutputStream().flush();
p.getOutputStream().close();
p.waitFor();
}
}
I'd use a Stream Gobbler. For more on that, please look here: What to do when Runtime.exec() won't
You cannot "ignore" the output of a child process in Java, well at least technically. You ought to read the contents of the input stream, for not doing so will result in the output buffer on the other end filling up, resulting in the described hanging behavior. When the child process attempts to write to a full output buffer, it will block until the buffer has been cleared by reading it.
If you do not want the output, at least read it and discard it. Or use a NullInputStream. You do not have to use Apache Commons class; you can build your own NullInputStream class whose read methods have empty bodies, similar to NullOutputStreams.
Also, this problem might not be solved by reading the input stream alone. You would have to read the error stream as well, which may be redirect to the input stream.