Reputation: 21
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?
Upvotes: 2
Views: 3448
Reputation: 408
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"});
Upvotes: 1
Reputation: 39
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();
}
// ...
}
Upvotes: 0
Reputation: 527
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.
Upvotes: 0
Reputation: 3563
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\"");
Upvotes: 1
Reputation: 201409
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();
}
Upvotes: 0