I am not a programmer and I need to fix some code to solve a problem.
The problem is that the app does not read file paths with spaces.
Code:
private void jMenuHELPActionPerformed(java.awt.event.ActionEvent evt) { //GEN FIRST:event_jMenuHELPActionPerformed
try {
Runtime.getRuntime().exec("cmd /c start "+" C:\Users\rafi\Documents\Name with spaces\file.txt");
} catch (IOException ex) {
ex.printStackTrace();
}
// ...
}
When I try to open a file from within the app, it opens a window with the following error:
Windows cannot `find C:\Users\rafi\Documents\Name`. Make sure that the name is correct.
It reads the path only to the first space.
How can I solve this problem?
Try putting the path in quotes. On the command line different parameters are separated by whitespace, and thus the path needs to be surrounded by quotes to indicate it is a single parameter.
Runtime.getRuntime().exec("cmd /c start \"C:\\Users\\rafi\\Documents\\Name with spaces\\file.txt\"");
Use the exec method that takes an array of arguments instead. Don't forget you also need to escape your backslashes.
Runtime.getRuntime().exec(new String[] {"cmd", "/c", "start", "C:\\Users\\rafi\\Documents\\Name with spaces\\file.txt"});
You need to escape the \ characters and Desktop.open(File) is how I would use the operating system to open a given file with its' default application for that file type.
File file = new File("C:\\Users\\rafi\\Documents\\Name with spaces\\file.txt");
try {
Desktop.getDesktop().open(file);
} catch (IOException e) {
e.printStackTrace();
}
Have you tried doing:
private void jMenuHELPActionPerformed(java.awt.event.ActionEvent evt) {//GEN FIRST:event_jMenuHELPActionPerformed
try {
Runtime.getRuntime().exec("cmd /c start "+" C:\Users\rafi\Documents\Name\ with\ spaces\file.txt");
} catch (IOException ex) {
ex.printStackTrace();
}
}
That should escape the space character, instead of putting with and spaces\file.txt as arguments.
You update your code folowing below:
private void jMenuHELPActionPerformed(java.awt.event.ActionEvent evt) { //GEN FIRST:event_jMenuHELPActionPerformed
try {
Runtime.getRuntime().exec("cmd /c start "+" C:\\Users\\rafi\\Documents\\Name with spaces\\file.txt");
} catch (IOException ex) {
ex.printStackTrace();
}
// ...
}
Related
I have an executable that generates some file, and I need to call this executable from a Java application. The command goes like this
Generator.exe -outputfile="path/to/file" [some other params]
It works fine on the command prompt, but running it from Java,all steps are executed (which means the executable was called properly), but the file is not created, here is my code:
try {
Runtime.getRuntime().exec(new String[]{"path/to/Generator.exe", "-outputfile=path/to/file", param1, param2,..etc});
}
catch (Exception e) {
e.printStackTrace();
}
I got no errors in the exe log,and I have no way to debug it, but this seems as a problem with my java application, I see that I am trying the same exact command.. what am I missing?
I have a second approach for you. Try with the below. Here you are creating a output.txt file to see the output from the exe file. If successful you can comment out that line. Hope this will help you.
String[] command ={"path/to/Generator.exe", "-outputfile=path/to/file", "param1"};
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectOutput(new File("C:\\log\\output.txt"));
try {
Process p = pb.start();
p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}catch (Exception e1) {
e1.printStackTrace();
}
I'm creating a named pipe in Java, which is working with the following code:
final String [] mkfifo = {"/bin/sh", "-c", "mkfifo ~/myFifo && tail -f ~/myFifo | csh -s"};
Process p = Runtime.getRuntime().exec(mkfifo);
But now I'm getting a NoSuchFileException when I try to delete it with this code:
Path fifoPath = Paths.get("~/myFifo");
try {
Files.delete(fifoPath);
} catch (Exception e) {
System.err.println(e);
}
I have verified that the file is, indeed, being created by issuing an ls ~ during execution of the program, and ~/myFifo still remains after the exception is thrown and execution of the program ends.
I assumed the ... && tail ... may cause some problems in case that it is somehow blocking, so I made the change to creating the named pipe with this:
final String [] mkfifo = {"/bin/sh", "-c", "mkfifo ~/myFifo"};
Process p = Runtime.getRuntime().exec(mkfifo);
The pipe is still created, which is fine. I've also attempted to remove the pipe in a less-native Java way, via exec:
final String [] rmfifo = { "/bin/rm ~/myFifo" };
Runtime.getRuntime().exec(rmfifo);
None of these seem to work. Any ideas?
Thanks,
erip
The problem is the ~/myFifo.
Java isn't understanding the ~
I ran the following code.
Path fifoPath = Paths.get("/home/russell/myFifo");
try {
Files.delete(fifoPath);
} catch (Exception ex) {
System.err.println(ex);
}
And it ran perfectly.
String home = System.getProperty("user.home");
Path fifoPath = Paths.get(home + "/myFifo");
try {
Files.delete(fifoPath);
} catch (Exception ex) {
System.err.println(ex);
}
The above code also works on my system.
~/ is a shell thing, so java won't pick it up.
The reason it's actually creating the file in the first place is because you're using /bin/sh to run the mkfifo command, and sh translates the ~/.
I am trying to develop a Java tool to refactor css files. I am trying to access the command prompt from Java. The command prompt is opening fine but it's not running the csstidy exe file.
try {
String command = "cmd /c start cmd.exe /K \"cd C:/Users/BS11040/Desktop/CSSTIDY_JAVA/";
Process child = Runtime.getRuntime().exec(command);
OutputStream out = child.getOutputStream();
out.write("csstidy.exe /r/n".getBytes());
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
Try invoking your .exe directly, you are doing it way to complicated:
String command = "C:/Users/BS11040/Desktop/CSSTIDY_JAVA/csstidy.exe";
Process child = Runtime.getRuntime().exec(command);
And by the way, the codes for CR and NEWLINE are \n and \r , take care to use the right slash!
Issue:- If the executable command contain's any spaces then System.exec is omitting the string content after the first space.
For example:- if command="/opt/GUIInstaller/installers/abc def gh.bin"
Then java is executing command up-to /opt/GUIInstaller/installers/abc only and resulting a error like java.io.IOException: "/opt/GUIInstaller/installers/abc": error=2, No such file or directory
protected void launch(final String command)
{
try
{
if(command.contains("null"))
{
logger.error("Installer is not located in the specified folder: "+command);
System.exit(0);
}
runTime.exec(command);
}
catch (IOException ioException) {
logger.error(ioException.getMessage(), ioException);
}
}
Is I am doing any mistake, please help me to solve this issue.
Environment:- Java7 update9 + RHEL6
As described in the javadocs of Process#exec(), exec(String) simply splits the given command string into tokens via StringTokenizer. If you do that job jourself by passing tokens to exec(), spaces in there are no problem:
runTime.exec(new String[] {"/opt/GUIInstaller/installers/abc def gh.bin", "--param1=foo"});
Add
if(command.contains(" ")){command.replace(" ","\\ ");}
before the runTime.exec(command);
This basically just replaces spaces with escaped spaces..
Edit:
Or to make it smoother try to execute this
runTime.exec(command.replace(" ","\\ "));
without adding the aforementioned line..
In Java I want to execute a .lnk shortcut which it self executes a .exe file.
I run the executable like so:
String currentDir = new File(game.getGamePath()).getCanonicalPath();
ProcessBuilder processBuild = new ProcessBuilder(currentDir);
processBuild.command("cmd", "/c", "start" , currentDir);
Process = processBuild.start();
try {
Process.waitFor();
} catch (InterruptedException ex) {
Logger.getLogger(AuroraLauncher.class.getName()).log(Level.SEVERE, null, ex);
}
I want the waitFor() thread blocking method to wait until the actual executed application (.exe file) terminates before it continues not the shortcut. Is there a way to do this simply or do I have to somehow extract the .exe path from the .lnk? if so how would I do that?
"start" launches a separate process, so your process is done. But you can extract the actual executable path from the lnk file. take a look at this post.
Windows command "start" has an option /wait you must specify to tell him it has to wait for the end of the process.
This code run until you close notepad:
#Test
public void run() throws IOException {
String currentDir = new File(System.getProperty("user.home"),"desktop/notepad.lnk").getCanonicalPath();
ProcessBuilder processBuild = new ProcessBuilder(currentDir);
processBuild.command("cmd", "/c", "start","/wait", currentDir);
Process p= processBuild.start();
try {
p.waitFor();
} catch (InterruptedException ex) {
}
System.out.println("process terminated!");
}
Simpler than to parse the lnk file.
Your code certainly won't compile. You should fix it to compile and work as intended:
Process p = processBuild.start();
try {
p.waitFor(); // Ignoring the process result code.
} catch (InterruptedException ex) {
Logger.getLogger(AuroraLauncher.class.getName()).log(Level.SEVERE, null, ex);
}