问题描述
我一直使用以下代码在Windows机器上使用Java打开Office文档,PDF等,并且运行正常,但出于某种原因,当文件名将其嵌入多个连续的空格(例如“ File [SPACE] [ SPACE] Test.doc的”。
我该如何进行这项工作? 我不反对编写完整的代码...但是我不希望将其替换为调用JNI的第三方库。
public static void openDocument(String path) throws IOException {
// Make forward slashes backslashes (for windows)
// Double quote any path segments with spaces in them
path = path.replace("/", "\\").replaceAll(
"\\\\([^\\\\\\\\\"]* [^\\\\\\\\\"]*)", "\\\\\\\"$1\"");
String command = "C:\\Windows\\System32\\cmd.exe /c start " + path + "";
Runtime.getRuntime().exec(command);
}
编辑:当我用错误的文件运行它时,Windows会抱怨找不到文件。 但是...当我直接从命令行运行命令行时,它运行得很好。
1楼
如果您使用的是Java 6,则可以使用的使用当前平台的默认应用程序启动文件。
2楼
不知道这是否对您有很大帮助...我使用Java 在Java程序中启动外部Shell脚本。 基本上,我会执行以下操作:(尽管这可能并不适用,因为您不想捕获命令输出;您实际上想启动文档-但这也许会激发您可以使用的功能)
List<String> command = new ArrayList<String>();
command.add(someExecutable);
command.add(someArguemnt0);
command.add(someArgument1);
command.add(someArgument2);
ProcessBuilder builder = new ProcessBuilder(command);
try {
final Process process = builder.start();
...
} catch (IOException ioe) {}
3楼
问题可能出在您使用的“启动”命令,而不是文件名解析。 例如,这似乎在我的WinXP机器上运行良好(使用JDK 1.5)
import java.io.IOException;
import java.io.File;
public class test {
public static void openDocument(String path) throws IOException {
path = "\"" + path + "\"";
File f = new File( path );
String command = "C:\\Windows\\System32\\cmd.exe /c " + f.getPath() + "";
Runtime.getRuntime().exec(command);
}
public static void main( String[] argv ) {
test thisApp = new test();
try {
thisApp.openDocument( "c:\\so\\My Doc.doc");
}
catch( IOException e ) {
e.printStackTrace();
}
}
}