I have a C code which I have compiled and added to path in order to be able to execute it form anywhere (I've double checked that I can do that)
Now I want to do a GUI to work with it in an easier way. I ask the user to input a file and an output directory.
In a click button I put the code to execute the command from the GUI:
String command = "myprogram -e " + file;
new ExecuteShellInstruction().main(command,jTextOutputDirectory.getText());
I execute the code in other class:
p = Runtime.getRuntime().exec(command, null, new File(directory));
But I always get this error:
java.io.IOException: Cannot run program "myprogram" (in directory "/Users/user_name/Documents/folder/example"): error=2, No such file or directory
I've checked that if I write exactly the same from the same folder there is no problem.
Any idea of what I'm doing worng?, If obtained this way of doing it from a question which was marked as correct, maybe I'm missing something, but I've already been 1 hour trying things and nothing seems to work.
Thank you!
Finally I found a solution.
It seems like you have to tell that your application can be executed by adding "./" at the beginning. Something like this:
String command = "./myprogram -e " + file;
Related
So I spent half a day trying to get this to work with no positive result. I am using a Java ProcessBuilder to execute some .exe file with a couple of arguments, but the file-path contain space(s) and somehow I can't get it to work properly. I have checked a number of other SO posts and implemented solutions like surround code with escaped quotes and splitting it up in command and arguments etc. My code is below:
try {
ProcessBuilder pBuilder = new ProcessBuilder(
// Main Command.
"C:\\namewith space\\database\\postgres_db\\bin\\pg_ctl.exe",
// Command Parameters.
"start",
"-D C:\\namewith space\\database\\database",
/*The quotes in the next argument are necessary, the -o stands for 'options' and everything between the quotes are the actual database parameters which to start the Database with.*/
"-o \"-p 15000\"",
"-l C:\\namewith space\\database\\postgres_db\\bin\\postgres_log.txt");
File log = new File("\"C:\\folder\\log.txt\"");
pBuilder.redirectErrorStream(true);
pBuilder.redirectOutput(Redirect.appendTo(log));
Process p = pBuilder.start();
} catch (IOException ex) {
System.out.println("Exception Occurred: " + ex);
}
I have tried so far:
Surrounding and not surrounding each/any of the paths in the above code with escaped quotes just in case that matters (something tells me it does...).
Using the Runtime.getRuntime().exec("full command with/without any/all escaped quotes"); method, but when searching on SO I found out everyone is saying you should use the ProcessBuilder instead.
Adding parts of the above code together in different ways in the ProcessBuiler's first command String, like "\"C:\\namewith space\\database\\postgres_db\\bin\\pg_ctl.exe\" start"
The files are 100% located at the given paths, I checked this by hand and by pasting the paths in the File Explorer over 10 times.
Splitting up the command into setting the working directory of the command to C:\namewith space\ and then adding the args without that part.
The error (via the System.out.println("Exception Occurred: " + ex); ) I keep getting is: java.io.IOException: Cannot run program "C:\namewith space\database\postgres_db\bin\pg_ctl.exe": The filename, directory name, or volume label syntax is incorrect.
Please let me know if you need any extra parts/code and I will do my best to provide it in detail.
Try to break the problem down.
First just read the absolute path shown in the IOException into a File object and call the exists() method to check that the file really exists and the JVM has access to it.
If that didn't work, fix your path or the access permissions. If the file really exists and you can access it then create the ProcessBuilder without any parameters, just with absolute path to your exe.
You shouldn't get the IOException now. Then add the parameters one by one. If you find one that breaks the thing, then fix the parameter (maybe the double quotes are missing) and go onto the next until you finish.
I am new one for R language and question is related to R language.
I created simple Java program which is used to check the file is available or not.
String sampleCSVFileLocation = "source/SampleCSVFile.csv";
File file = new File(sampleCSVFileLocation);
if (file.exists())
{
System.out.println(sampleCSVFileLocation + " is available");
}
else
{
System.out.println(sampleCSVFileLocation + " is not available");
}
I convert this program as Test.jar and stored into this location C:\Demo.
and I put the SampleCSVFile into the same location.
This is my file structure:
C:/Demo/Test.jar
C:/Demo/source/SampleCSVFile.csv
I run this code from command line and am getting the correct output and it goes to IF block.
C:\Demo>java –jar Test.jar
source/SampleCSVFile.csv is available
My Problem is:
I run the same jar from R language. I am getting wrong output. It goes to else block.
>system(“java –jar C:/Demo/Test.jar”)
source/SampleCSVFile.csv is not available
It unable to refer the source folder path.
I don’t want change the java code.
How to resolve this issue.
Help me.
Thanks in advance.
Try to set working directory, before exec jar.
setwd("C:/Demo")
More information here -http://stat.ethz.ch/R-manual/R-patched/library/base/html/getwd.html
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.
I know that the system property "user.dir" returns the current working directory; the directory containing that file that is currently running.
I am wondering, how would I be able to go one step farther? I need to find the current working file. I am writing a little app that is kind of like an auto-updater, and I need to know the file that needs to be updated. For example, if I run a file from C:/test.jar I want to actually know, in code, that the current location of the file that is running is C:/test.jar so that I can write (new) data to it.
I've tried an approach like this:
ClassLoader loader = Test.class.getClassLoader();
System.out.println(loader.getResource("Test.class"));
However, it prints out:
3/5/12 7:50:16.914 PM [0x0-0x31031].com.apple.JarLauncher: rsrc:Test.class
(I am running this on a Mac - I got that line from the Console).
Any help is greatly appreciated. Thanks!
With credits to Fab in the following post:
Jar path+name from currently running jar
String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");
This will print the current file's path.
File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
System.out.println(f.getPath());
I'm running a windows program from within java:
String command = "cmd /C start "+fileName+".bat";
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(command, null, new File(currWD));
int exitValue = pr.waitFor();
The program completes successfully (exitValue == 0) and creates a file "fileName" in the working directory. I am trying in the same routine to find the size of this file:
xmlFileSize = (new File(fileName)).length();
Java finds the file yet it appear to be empty (xmlFileSize == 0). Once Java finishes I can see, however, that the file is non-empty.
How can I resolve this? All I want is that Java can correctly assesses the size of the file created by the windows program that Java has executed.
A zero-length file indicates that the file may not exist. From the docs:
The length, in bytes, of the file denoted by this abstract pathname, or 0L if the file does not exist.
Note that you use currWD as working directory for your bat-file. You could try to do:
new File(currWD, fileName).length()
to make sure you look for the file in the right directory.
It probably has to do with executing the bat file from a command shell. What does the bat file do? Is it launching a program?
I'm guessing that the script calls or executes another program and returns which allows the shell to die. This in turn let's the java process continue while the process from the script continues executing asynchronously.
According to the Java API for Process, that's allowable which it most definitely should be (link java.lang.Process)
I credit this answer to aioobe and John. As John suggests, the external program started by the batch file spawns a process that seems to be running for a while (50-300 millisec) after the Java sub-process running the batch file has returned. I resolved the problem by introducing a pause (as suggested by aioobe) :
int exitValue = pr.waitFor();
try {Thread.currentThread().sleep(300);} catch (InterruptedException e) {e.printStackTrace();}
After the pause Java seems to be able to see the files created by the external program. Thanks again to both contributors who helped me resolve this issue!
If anyone finds a more elegant solution, please, feel welcome to post.