I am trying to run the following code from within Eclipse:
Process process = Runtime.getRuntime().exec("gs");
However I get the exception:
java.io.IOException: Cannot run
program "gs": error=2, No such file or
directory
Running gs from the command prompt (OS X) works fine from any directory as it is on my PATH. It seems eclipse doesn't know about my path environment variable, even though I have gone into run configurations and selected PATH on the environment tab.
In additional effort to debug this issue I tried the following code:
Process process = Runtime.getRuntime().exec("echo $PATH");
InputStream fromStdout = process.getInputStream();
byte[] byteArray = IOUtils.toByteArray(fromStdout);
System.out.println(new String(byteArray));
The output was $PATH, hmm. Can someone nudge me in the correct direction?
you are assuming that exec() uses a shell to execute your commands (echo $PATH is a shell command); for the sake of simplicity you can use System.getenv() to see your $PATH:
System.out.println(System.getenv("PATH"));
EDIT
Often a better and flexible alternative to Runtime.exec() is the ProcessBuilder class.
I had the same issue and i found the problem. The Path Variable in Eclipse had different content than the one from the command Line.
Solution:
Look up for the $Path variable in command Line and copy the content. Then open Run Configuration->Environment and select new. Name: $PATH Value: insert the copied content.
That solved the Problem.
Related
I am executing wkhtmltopdf command line tool from Java but it is throwing below error.
Cannot run program "wkhtmltopdf": error=2, No such file or directory
But note that when I execute this command line tool from my mac terminal then pdf got generated successfully. Please see below.
MacBook-Air-2:~ inDiscover$ wkhtmltopdf /var/folders/7y/2vr28n113p908ksnk0fnpqch0000gn/T/test7896850081571855407.html /Users/mymac/Documents/Project/emailbody/test2.pdf
Loading pages (1/6)
Counting pages (2/6)
Resolving links (4/6)
Loading headers and footers (5/6)
Printing pages (6/6)
Done
I have seen lot many similar questions here (for ex: wkhtmltopdf: No such file or directory [ Closed ]) but issue with those questions are related to $PATH. In my case I believe that I have set the path to the executable to $PATH correctly. Please see below.
MacBook-Air-2:~ inDiscover$ locate wkhtmltopdf
/private/var/db/receipts/org.wkhtmltopdf.wkhtmltox.bom
/private/var/db/receipts/org.wkhtmltopdf.wkhtmltox.plist
/usr/local/bin/wkhtmltopdf
/usr/local/share/man/man1/wkhtmltopdf.1.gz
You can see here wkhtmltopdf has been added to $PATH (/usr/local/bin)
Also , see below the response for echo $PATH.
MacBook-Air-2:~ inDiscover$ echo $PATH
/Users/mymac/anaconda/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
MacBook-Air-2:~ inDiscover$
I am getting this issue only when I try to execute the command from Java. Please see my java code below.
String VIEWPORT_SIZE = "2480x3508";
int CONVERSION_DPI = 300;
int IMAGE_QUALITY = 100;
List<String> cmd = new ArrayList<String>(Arrays.asList("wkhtmltopdf",
"--viewport-size", VIEWPORT_SIZE,
"--enable-local-file-access",
// "--disable-smart-shrinking",
"--dpi", String.valueOf(CONVERSION_DPI),
"--image-quality", String.valueOf(IMAGE_QUALITY)));
//cmd.addAll(extParams);
cmd.add("/var/folders/7y/2vr28n113p908ksnk0fnpqch0000gn/T/test7896850081571855407.html");
cmd.add("/Users/mymac/Documents/Project/emailbody/test3.pdf");
try {
ProcessBuilder pb = new ProcessBuilder(cmd);
if (Logger.level.compareTo(LogLevel.Info) >= 0) {
pb.inheritIO();
}
Process p = pb.start();
p.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
Am I really missing something?
Here are a few things you can check, one will hopefully resolve your issue.
Nearly all occasions I've seen where java is not finding an application that your shell or terminal does run are down to use of commands built into the shell / terminal (such as an alias), or because of PATH used in a script that you use to launch your java yourapp.ClassName ... is different to that set for the interactive shell / terminal.
The interactive shell / terminal may include or source from other scripts on startup - for example it may have run code in ~/.bashrc, ~/.login, ~/.profile, ... meaning that PATH declared inside interactive shell is not same as PATH presented to Java app when you launched it.
Hence you see terminal show PATH has /usr/local/bin:
MacBook-Air-2:~ inDiscover$ echo $PATH
/Users/mymac/anaconda/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
But Java says no /usr/local/bin in PATH:
System.out.println("PATH="+System.getenv("PATH"));
/usr/bin:/usr/sbin:/sbin
So to fix your problem you could make java use absolute path to run the app wkhtmltopdf:
Arrays.asList("wkhtmltopdf" -> Arrays.asList("/usr/local/bin/wkhtmltopdf" ...
OR you could make java launch your shell / terminal so the terminal sources its env scripts as normal and runs the command:
# Confirm which shell your Terminal uses:
echo $SHELL
If you have say SHELL=/bin/bash you can run /bin/bash from java and let it work out where wkhtmltopdf is:
Arrays.asList("wkhtmltopdf" -> Arrays.asList("/bin/bash", "-c", "wkhtmltopdf" ...
OR if you have a script say runMyApp.sh to launch your java app, set the PATH before java yourclass.Name,
export PATH=/usr/local/bin:$PATH
java yourclass.Name
OR if you have a script say runMyApp.sh to launch your java app, make that it sources the same profile environment as your Terminal does. This depends on the SHELL but for some systems could be something like:
#!/bin/bash
# Load env from current user - "source" and "." may or may not work in the SHELL you are using:
source ~/.bashrc
# OR maybe other shell
. ~/.somefilerc
echo $PATH # Now hopefully includes same /usr/local/bin
java yourclass.Name
Try to add sudo in the front of wkhtmltopdf.
I've made an executable jar file for a terminal game that can be opened by typing java -jar name.jar in the Terminal.
Then I made a .sh file inside the same folder as the jar file to open it by double-clicking the .sh. I asked how to do this here, where people told me to use the following code in the .sh.
#! /bin/bash
DIR=$(dirname "$0")
java -jar "$DIR/game.jar"
This worked for a while, but when I renamed the folder, I realised if I move the folder to a pen drive the whole thing stops working and I get this in the Terminal.
Error: Unable to access jarfile /Volumes/Hard
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.
[Process completed]
So how to find the file path to the folder the .sh and the jar are in, regardless of where it is, what its name is and what drive it is on?
Also, I'm using MacOS Mojave 10.14.4 if that's of any importance.
The error looks like the path does contain spaces, like probably /Volumes/Hard Drive/Users/something. The solution is to quote the command substitution.
Tangentially, don't use upper case for your private variable names.
But of course, the variable isn't really necessary here, either.
#!/bin/sh
java -jar "$(dirname "$0")/game.jar"
Nothing in this script uses Bash syntax, so it's more portable (as well as often slightly faster) to use sh in the shebang. Perhaps see also Difference between sh and bash
You can store the full path of the working directory using the environement variable $PWD, like in this example (done in 5min, it is just to show you how it is works) :
#!/bin/bash
DIR=$PWD
gamePath='java -jar '$DIR'/game.jar'
echo $gamePath
Wherever I will execute this script, it will shows up the working directory even if I change the name of the parent. Let me show you :
You can see that $PWD environnment variable works great.
Now, I will change the directory name from TestFolder to TestFolderRenamed and execute the script again :
So, in your case, change your code as following :
#! /bin/bash
DIR=$PWD
java -jar "$DIR/game.jar"
It should works.
Environment: mac
Precondition: I already configured 'adb' full path to my bash_profile. and when I tried type 'adb' in my terminal, it is working.
But, I tried to exec 'adb' command from java, 'adb' is not working, instead I need to pass the full adb path to make it work.
I guess this is probably something to do with the bash_profile setting, anyone know the exact reason for this issue?
Runtime.getRuntime().exec() runs /bin/sh -c <command>. If this is or points to a bash shell on your system: A non-interactive bash does not read .bash_profile unless explicitly (--login) told to do so.
From the documentation:
When Bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior.
It's a little convoluted, but non-interactive, non-login bash instances don't read the profile files.
Your path settings does not get picked up by the subshell (which is actually /bin/sh which might not even be bash at all).
If you want, you can add the path to adb system wide by adding an appropriate entry to to /etc/paths.d.
I am trying to make a eclipse project in Java to launch commands with some buttons. The libraries of Ros fuerte (These ones i want to use) are correctly installed and concretly i am trying to launch a ros command from a Java File using:
String cmd = "roscore";
Runtime rt = Runtime.getRuntime();
Process p = rt.exec(cmd);
If i launch this command from a current terminal it works, but if i do it from the java file i have a problem because the terminal doesnt recognize the command.
java.io.IOException: Cannot run program "roscore": java.io.IOException: error=2, No such file or directory
at java.lang.ProcessBuilder.start(ProcessBuilder.java:475)
at java.lang.Runtime.exec(Runtime.java:610)
at java.lang.Runtime.exec(Runtime.java:448)
at java.lang.Runtime.exec(Runtime.java:345)
at LaunchTerminal.main(LaunchTerminal.java:24)
I think that i need to add some path or similar but i dont find the information. Does anybody know how to do it?
Thank u.
only normal commands are possible to execute like rm or cd ... al others must be referenced with full path of context
Do the following if you are using the groovy distribution:
String cmd = "source /opt/ros/groovy/setup.bash && roscore";
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.