I have a shell script which I'm trying to call from Java. The shell script contains:
cat /dev/tty.USB0 > file.txt
In my Java code I am using:
Process p= Runtime.getRuntime().exec("/home/myname/Scrivania/capture.sh");
But it does not work. When I run it from the terminal it works as expected.
You can't directly execute a .sh script like this, since it's not an executable. Instead, you have to run /bin/sh -c /home/myname/Scrivania/capture.sh instead.
First of all, it's not a good style to work with OS-based features in Java code. Instead of that i suggest you to work with system input/output streams only. For example if your program should handle output of your script, you can do something like:
cat /dev/tty.USB0 > java YourMainClass
and then work directly with System.in.
Even if your program is more complicated than script output consumer, you can rewrite it to remove all OS-based parts from your program, it'll make your code more stable and maintainable.
What you are doing works. Well, it should.
My guess as to what is/seems wrong is this: You might be looking for the output file "file.txt" in the wrong place.
Here's a little experiment
System.out.println("Output file - " + new File("file.txt"));
Process p= Runtime.getRuntime().exec("/home/myname/Scrivania/capture.sh");
The first line should tell you where to look for your file.
P.S. Of course, do remember to import java.io.File :)
Related
I'm not sure what to tag this with, but I need help combining two commands into a single command. I've tried this with ant, but it doesn't perform as required (long story). Essentially I need
javac *.java
java org.junit.runner.JUnitCore filename
To be consolodated into a single command. Preferrably something like
ant
with an external build.xml file, however after several hours fiddling with Ant I've gotten it to work but not as required (I need continuous output to stdout during runtime). I'm fine with shell scripts, clever java tricks, anything. I'll take what I can get at this point.
Writing a shell script is really a trivial matter: just copy-paste those exact two lines into a file (say you call it myscript.sh) and you're done. Then you can run it with sh myscript.sh. For added convenience add a first line that says #!/bin/sh (the so-called "hash-bang" incantation), issue a chmod u+x myscript.sh, and then you can run it as any other command: ./myscript.sh.
BTW this turned out into a question unrelated to Java, you might retag it with a shell script-related tag.
everyone. I'm quite new here so please be tolerant if I make any mistakes.
I have a .bat file containing a command line to open up a .jar file that contains a program that has a GUI in it. The only line that's in the .bat file is:
java -jar "NewServer.jar"
I've been trying to use Runtime() to get this to run, but most the instructions I find to open a .bat file in a java program are for Windows. I'm currently using Fedora 12 (don't tell me to upgrade, I can't) if that makes a difference and programming using Eclipse. I also found this ProcessBuilder thing, but I couldn't get it to work so unless you have very explicit directions on how to use it, please don't include it in your answer. I would much rather use Runtime. It looked simpler.
Here's my code to test using Runtime in a java program. I'm hoping that if I can get this to work, I can get it to work in my real program.
import java.io.IOException;
public class testbat {
public static void main(String[] args) {
Process proc = null;
try {
proc = Runtime.getRuntime().exec("./ myServer.bat");
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Cool");
}
The last line is just there for me to see if the program actually ran in case the GUI doesn't open. Also, I've already tried many combinations of things to include in the area after ".exec". I've tried using a path like "~/user/workspace/ProjectServer/dist/myServer.bat" to no avail.
I also already know that .bat files are for windows, but I'm able to execute it in linux, so I don't know if that makes a difference. I also tried using a .sh file the same way and it didn't work.
Please bear in mind that I'm not that great at Java, but I had to use it for this particular program, so if your answers could be really descriptive that would be awesome.
Just take that line out of the bat file, and run it. Yo're making it too hard.
$ java -jar "NewServer.jar"
will work. The quotes aren't necessary, so
$ java -jar NewServer.jar
will work as well. If you want to have the equivalent of your bat file, create a file named, say, run_newserver containing that line. Change its mode to executable:
$ cat > run_newserver
java -jar NewServer.jar
^D
$ chmod a+x run_newserver
$ ./run_newserver
Ideally, since you shouldn't have scripts without comments, do this. In your favorite editor, create a file run_newserver containing
#!/usr/bin/env bash
java -jar NewServer.jar
and chmod that. The line with #! -- often called a "shebang line" -- is UNIX magic that lets you say what interpreter you want. The program env in usr/bin finds your program and runs it (needed because different systems put bash in different directories.)
You could even put explanatory comments in the file too.
I'm a little unclear why you want to use Runtime#exec to run it at all -- it seems you'll just need a shell script to start that program.
Why are you using Java to run a Batch file, that in turn runs a Java program? Why have Batch in the loop at all? Just put the jar in your classpath and call it directly.
Batch (.bat) files are only for Windows environment. So, Try using shell script
Process proc = Runtime.getRuntime().exec("myServer.sh");
Just open up terminal and do this
vi /dir/to/exec/exec.sh
tap "i" and write this
#!/bin/sh
java -jar "NewServer.jar"
or if you want to run it in the background
#!/bin/sh
java -jar "NewServer.jar" & > /tmp/JavaServer.log
hit esc and type ":wq" and you have saved the file.
type this into the terminal
chmod +x /dir/to/exec/exec.sh
this give executable privileges and then you should run the file like
sh /dir/to/exec/exec.sh
Process is only initialized by your first call. You need to run:
proc.waitfor();
to get it to actually run your app.
I currently have the following batch script I want to run from my Java program:
"C:\Program
Files\Java\jdk1.6.0_25\bin\java.exe"
-classpath "D:..."
Main >
"...\result.out"
Now, I've done a simple
Runtime.getRuntime().exec(command);
where command is that string I have shown above. The problem is that it is simply calling java.exe with the shown arguments, instead of calling the console with the given arguments. The difference is subtle, for if it is calling directly java.exe it will ignore the redirect of the output stream!
Is there a easy way to do this? I've tried prefixing command with "cmd " but that didn't seem to help.
I'd like to stay away from having to read the output stream and then having to manually save this to a file.
Thanks
To solve the issue,
cmd /c "command"
is enough.
Process proc = Runtime.getRuntime().exec("acpi -b");
Now you can use proc.getInputStream() and proc.getOutputStream() like any normal input and output streams.
You can then write the contents to your output file.
This is the method I mostly use.
I am trying to build a very simple python script to automate minifying/combining some css/js assets.
I am not sure how to properly handle the minification step. I use yui-compressor and usually call the jar directly from the command line.
Assuming the build script is in the same directory as rhino js.jar and yui-compressor.jar, I'd be able to compress a css/js file like so:
java -cp js.jar -jar yuicompressor-2.4.4.jar -o css/foo.min.css css/foo.css
Calling that from the terminal works fine, but in the python build file, it does not
eg, os.system("...")
The exit status being returned is 0, and no output is being returned from the command (for example, when using os.popen() instead of os.system())
I'm guessing it has something to do with paths, perhaps with java not resolving properly when calling to os.system()… any ideas?
Thanks for any help
I have a somewhat similar case, when I want a python program to build up some commands and then run them, with the output going to the user who fired off the script. The code I use is:
import subprocess
def run(cmd):
call = ["/bin/bash", "-c", cmd]
ret = subprocess.call(call, stdout=None, stderr=None)
if ret > 0:
print "Warning - result was %d" % ret
run("javac foo.java")
run("javac bar.java")
In my case, I want all commands to run error or not, which is why I don't have an exception raised on error. Also, I want any messages printed straight to the terminal, so I have stdout and stderr be None which causes them to not go to my python program. If your needs are slightly different for errors and messages, take a look at the http://docs.python.org/library/subprocess.html documentation for how to tweak what happens.
(I ask bash to run my command for me, so that I get my usual path, quoting etc)
os.system should return 0 when the command executes correctly. 0 is the standard return code for success.
Does it print output when run from the command line?
Why would you want to do this in Python? For tasks like this, especially Java, you are better off using Apache Ant. Write commands in xml and then ant runs for you.
Dear all
I want to execute a EXE file in Java, but I was not able to do it correctly.
Originally, in DOS command prompt, my command is like this:
C:>\crf_test.exe model <inputfile.txt> outputfile.txt
Note: the input file name must be place in the brackets <>. It always gave me good results when run it in DOS window.
When I want my java program to call above command, I do like this:
Process p = Runtime.getRuntime().exec("crf_test.exe model <inputfile.txt> outputfile.txt");
However, the output of this command is "no such file or directory: "
I guest Java doesn't like the brackets <> in DOS command. I also remove <> out, but exe file did not accept that.
So now how can I deal with this problem? Please give me a sollution
Thank you much much
There are potentially two problems. Firstly, the one that others have mentioned - crf_test.exe may not be in your path. It's hard to tell whether your output of "no such file or directory" is from crf_test.exe or from Java trying to find crf_test.exe.
Secondly though, running it from DOS you're not really putting the filename in brackets - you're redirecting system input from the input file to the output file, so the logical grouping is:
crf_test.exe model < inputfile.txt > outputfile.txt
Now when you're running it from Java, it's genuinely trying to pass <inputfile.txt> as a second command-line argument, and outputfile.txt as a third. My guess is that crf_test.exe is then trying to load those as files, and giving "no such file or directory" as an error.
You'll need to load the data from inputfile.txt yourself and pass it in via Process.getOutputStream, and then read the output from Process.getInputStream and write it to outputfile.txt.
Alternatively, you could run cmd.exe and pass in the whole command as an argument - that way the shell will perform the redirection for you as if you were running from a DOS prompt.
The angle brackets are redirection operators: <inputfile.txt causes the input to be read in from inputfile.txt instead of the keyboard, >outputfile.txt causes the output to be written to outputfile.txt instead of the screen. This facility is provided by the shell, however when invoking your program with the Java runtime the shell is not present. Invoke via the shell, like this:
Runtime.getRuntime().exec("cmd /c crf_test.exe model <inputfile.txt> outputfile.txt");
...or redirect input and output using facilities provided by Java; see e.g. this question.
try this
Process p = Runtime.getRuntime().exec("crf_test.exe","/c","model outputfile.txt");
The problem is that the crf_test.ext is missing in your current execution folder. You need either copy the executable or use the absolute path or set the PATH variable to include the necessary path.
If I understand the problem right, you want to call
crf_test.exe model
with input from file inputfile.txt and output to outputfile.txt
You have to redrect in and out and call only crf_test.exe model. How do redirect in and out is described in how to redirect stdin to java Runtime.exec ?