Having an Issue with running gnuplot processes from Java - java

I'm having some trouble running gnuplot processes from Java. I'm creating a gnuplot script file, and then running it from within a java program. I've tried using both Process Builder and building a precess using Runtime.getRuntime().exec("blah blah..."), and neither have the full capability to work. The funny thing is is that using Runtime to make the process works almost perfectly, as long as the image file I'm creating via gnuplot isn't being saved to a directory without a space in it's name. ProcessBuilder doesn't work at all, however, and gives me the error: "CreateProcess error=2, The system cannot find the file specified"
It's taken me far too long to figure this stuff out, and so any help would be appreciated.
The code I use is here:
File script = new File("Demo.plt"); //Script file that outputs to a PNG file
//This works as long as the script file doesn't output to a png with a space in it's filepath
Process aProcess = Runtime.getRuntime().exec("gnuplot " + script.toString());
Thread.currentThread().sleep(1000);
aProcess.waitFor();
//This doesn't work at all
ProcessBuilder builder = new ProcessBuilder("gnuplot " + script.toString());
builder.redirectErrorStream(true);
Process process = builder.start();
And I know that the script works if run outside of Java, regardless of the spaces in the output line. I've even tried using '\ ' (the escape character for a space) and that doesn't work either. In fact, here is the code that I use:
String graphName = "DemoGraph";
//Isolate the FilePath
String path = script.getPath();
path = path.replace(script.getName(),"");
path = path.replace(File.separator, "\\\\"); //Gets around any parsing errors in filepaths on Windows
path = path.replace(" ", "\\ "); //Should get around parsing errors with spaces in gnuplot, but it seems to be irrelevant.
scriptFileWriter.write("set output \"" + path + graphName + ".png\"\r\n");
It's got to be an issue with java, because the scripts run from the Windows command line, and from the gnuplot command line, and frun being run by double-clicking the

I forgot to put quotes around the file name. It was a STUPID error.

Related

findstr not working in Java, How to fix it?

I'm working on a project and part of it must search words in some raw files of tagged text. For this, I'm trying to use the "findstr" function but It's been giving me lots of trouble.
The file contains text in spanish so in order to deal with the special characters I have to use the "findstr" function with some options.
I'm trying to run the command by ProccesBuilder and Process class but nothing It's happening.
I suspected that maybe there was a problem with the actual work directory so I changed It in the ProcessBuilder object that I have but with no results.
private static void findWordData(String filename){
try{
String procs = "findstr /g:" + filename + " spanishEtiquetado* >results.txt";
ProcessBuilder proBuild = new ProcessBuilder();
proBuild.command("cmd.exe","/c",procs);
proBuild.directory(new File("resources/TextData/SPA/"));
Process p= proBuild.start();
} catch (IOException e) {
System.out.println("exception happened - here's what I know: ");
e.printStackTrace();
System.exit(-1);
}
}
The expected result is that the command reads the word in the file after the /g: tag and then searches it through all the files that begin with "spanishEtiquetado". Finally, the results should be written in a file "results.txt":
Thanks for your time.
EDIT:
Ok this is weird.
As you can read in the comments, I created a new project so I could test things better and something weird It's happening.
Right now, I have the aux_string.txt, results.txt and the spanishEtiquetado file both in the root folder of the project and src folder of the project.
As code I have been testing two options:
First, the one that SuperMario48 posted a bit modified:
Runtime.getRuntime().exec("cmd /c findstr /g:aux_strings.txt spanishEtiquetado* >results.txt");
The second one is the one I was using before:
String procs = "findstr /g:" + filename + " spanishEtiquetado* >results.txt";
ProcessBuilder proBuild = new ProcessBuilder();
proBuild.directory(new File("src/"));
proBuild.command("cmd.exe", "/c", procs);
Process p = proBuild.start();
If the first one is executed the files that are located in the root folder are treated by the command and thus the results.txt file in the root folder is modifided with the wanted results.
Now, If I use my old code the directory change happens and a results.txt is written in the src folder but it's empty because the other necesary files are not readed, not even those that are outside the src folder.
I don't hace any idea of what is happening, any help appreciated.
Maybe try this. Just another kind of executing an external process.
Runtime.getRuntime().exec("cmd /c findstr /g:" + filename + " spanishEtiquetado* >results.txt");
Replace your try block with that to test.

"Cannot run program" when using Runtime.exec with spaces in program filename

I am using the below code to open the "sample.html' file.
String filename = "C:/sample.html";
String browser = "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe";
Runtime rTime = Runtime.getRuntime();
Process pc = rTime.exec(browser + filename);
pc.waitFor();
However, I am getting the below error.
java.io.IOException: Cannot run program "C:/Program": CreateProcess error=2, The system cannot find the file specified
Could someone please help me figure this. Thanks in advance.
Runtime.exec(String) automatically splits the string at spaces, assuming the first token is the command name and the rest are command line parameters. Also you do not have a space between browser and file, although that is not the root cause of the problem.
It thinks you want to run "C:/Program" with two command line arguments:
"Files"
"(x86)/google/Chrome/Application/chrome.exeC:/sample.html"
Use Runtime.exec(String[]) instead, that way you have full control over what is what:
String[] command = new String[]{browser, filename};
Runtime.exec(command);
Try this.
String filename = "C:\\sample.html";
String browser = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe";
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec(new String[] {browser, filename});
} catch (IOException e) {
e.printStackTrace();
}
Stop using Runtime.exec(String) - the problem is in how it processes the single string input.
The error message indicates how/where it is failing: note that it stops after "C:/Program" (or, the first space). This indicates that exec parsed the string "incorrectly" and thus isn't even looking for the correct executable.
Cannot run program "C:/Program"
Instead, consider the use of ProcessBuilder. While the usage is still system-dependent, ProcessBuilder allows separation of the executable file-name (and need to deal with it specially) and the arguments and does it's darnedest to invoke the target correctly.
String filename = "C:\\sample.html";
String browser = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe";
ProcessBuilder pb = new ProcessBuilder(browser, filename);
// setup other options ..
// .. and run
Process p = pb.start();
p.waitFor();
From what I can tell, in Windows, ProcessBuilder will wraps the individual components in quotes; this can create a different problem when arguments contain quotes..
Parameters must be passed separately:
Process pc = rTime.exec(new String[]{browser, filename});
Using exec() is not like using the command line - you can not use spaces to delimit the command from its parameters. Your attempt would try to execute a command whose path was the concatenation of the exec and the filename as one giant string.

Java: run executable program whit particular parameters

I need to run executable progam (.exe) in java. This program have two different operating modes: GUI and Command line. The syntax to launch the program from the command line is as follows :
C:\Users\Ermanno\Desktop\ "programFolder"\"program.exe" /stext output.txt
in this way the program store the outoput in the file "output.txt".
I tired it:
Process p = new ProcessBuilder("C:\\Users\\Ermanno\\Desktop\\programFolder\\program.exe" ,"/stext a.txt").start();
does not create the output file.
I also tired to use a file batch that contains the command and run it to java but the result is the same.
You need to pass each argument in a single string:
... program.exe", "/stext", "a.txt")...
Also make sure that you start a background thread which reads the output of the child process. If there is a problem, then the child will print an error message to it's standard output and if you don't actively read it, then this output will be lost.
For this, loop over the streams p.getInputStream() and p.getErrorStream().
The latter is especially important since you say "I also tired to use a file batch". Java doesn't do anything different than a batch script. If you can't run the command from batch, it won't work from Java, either.
My experience was horrible with using the JDK ProcessBuilder and Runtime.getRuntime().exec. I then moved to Apache commons-exec. Here is an example:
String line = "AcroRd32.exe /p /h " + file.getAbsolutePath();
CommandLine cmdLine = CommandLine.parse(line);
DefaultExecutor executor = new DefaultExecutor();
int exitValue = executor.execute(cmdLine);
I solved using file bath. This file contains the command.
String [] _s = {"cmd.exe", "/c", "start", "file.bat"};
Process pr = Runtime.getRuntime().exec(_s);

How to run bat file from java with arguments (i.e file name with full path) having folder name with space

Am trying to execute the a bat file with some arguments through a JAVA programmes . the arguments are file name with full path, And this path had some folder name with space, which are creating issue and giving me the following error
Error: 'D:\Documents' is not recognized as an internal or external
command
the code is as below
String command = "D:\Documents and Settings\ A.bat" + " " D:\Documents and Settings\B.xml
1. process = Runtime.getRuntime().exec(new String[] {"cmd.exe","/c",command});
2. process.waitFor();
3. exitValue = process.exitValue();
You need to escape the \ in your string (i.e. doubling them: D:\\Documents), but that is not the problem. You can try to escape the spaces Documents\\ and\\ Settings or you use the exec method that does this for you. Just dont build the command line by yourself. Better use ProcessBuilder for starting processes.
String command = "\"D:\Documents and Settings\\" A.bat" + " \"D:\Documents and Settings\B.xml\""
Escape double quotes, so you can include double quotes in the literal, to give:
cmd.exe /x "D:\Documents and Settings\" A.bat "D:\Documents and Settings\B.xml"
I was trying to do the same thing. I googled whole day but didn't make it work. At Last I handled it in this way, I am sharing it if it comes to any use of anybody :
String command = "A.bat D:\\Documents and Settings\\B.xml";
File commandDir = new File ( "D:\\Documents and Settings ");
String[] cmdArray = { "cmd.exe", "/c", command };
1. Process process = Runtime.getRuntime().exec( cmdArray, null, cmdArray );
2. process.waitFor();
3. exitValue = process.exitValue();
I've spent a while searching on SO and the wider Internet and was about to post this as a new question when I came across this, which does seem identical to my issue...
I am trying to call a Windows batch file from Java. The batch file takes several arguments but just the first, which is a path to a data file, is of relevance to this problem. The cut-down command line that I have been experimenting with is essentially:
cmd /c c:\path\to\my\batchfile.bat c:\path\to\my\datafile.mdl
I'm using Apache Commons Exec which ultimately delegates to Runtime.getRuntime().exec(String[] cmdarray, String[] envp, File dir), the 'correct' version as opposed to the overloaded versions taking a single String command. Quoting of the arguments when they contain spaces is therefore taken care of.
Now, both the path to the batch file and/or the path to the data file can have spaces in them. If either the path to the batch file or the path to the data file have spaces in, then the batch file is executed. But if both have spaces in them then the path to the batch file is truncated at the first space.
This has to be a (Java or Windows?) bug, right? I've debugged right down to the native call to create() in java.lang.ProcessImpl and all seems ok. I'm on JDK1.6.

Java command Runtime.getRuntime().exec() in Mac OS

I´m using Mac OS Lion, with java version 1.6.0_26
I'm making a small app for Mac in Java with a main menu for the user, so he can choose several options.
One of them is install an app using a .pkg
Everything was working fine with these commands:
File instFolder = new File(System.getProperty("user.dir") + "/foldername/appInstaller.pkg");
String s = "open "+ instFolder.toString();
Process p = Runtime.getRuntime().exec(s);
Then I realized that there is a problem when foldername has spaces or if I copy this java file with the needed subfolders to a USB pen drive with "NO NAME" as name (or some name with spaces).
Because s will become something like:
open /Volumes/NO NAME/foldername/appInstaller.pkg
or
open /Users/user1/Desktop/folder name/appInstaller.pkg
So when you run the p process, the command will finish where the first space appears on the path
open /Volumes/NO
or
open /Users/user1/Desktop/folder
To try to fix this I changed the s definition for something like this:
String s = "open "+ "\"" + instFolder.toString() + "\"";
It stopped working fine. The strange thing is that if i copy the s value (after creating the s variable) and paste it in the terminal it works:
open "/Users/user1/Desktop/folder name/appInstaller.pkg"
but running it from Java it does't work.
Could you help me, please?
Thanks.
In order to properly escape arguments, you can use the following:
Runtime.getRuntime().exec(new String[] { "open", instFolder.toString() });
Though I would probably to use the more modern ProcessBuilder:
ProcessBuilder pb = new ProcessBuilder("open", instFolder.toString());
Process p = pb.start();
int exitCode = p.waitFor();
Though this may be worth a read depending on what you want to do with the processes output.
Note: edited to reflect question in comment
it seems your path does not have quotes when turned into the shell.
You should probably add "'" on both sides of your path, so the final shell command will look like:
open 'your path'
instead of
open your path
Here's a little trick that came out from the answers mentioned above:
ProcessBuilder pb = new ProcessBuilder(commandString.split(" "));
Say commandString = "killall Mail" then the split will separate the words making it a String[] parameter to the ProcessBuilder.

Categories