我已经使用了下列代码打开办公室的文件,PDF等。在我的windows的机器使用Java和它的工作很好,除了因为某些原因当一个文件已嵌入它在它的多个连续的空间,如"文件的[空间][空间]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抱怨找到该文件。但是...当我运行命令行直接从命令行它运行很好。

有帮助吗?

解决方案

如果您使用的是Java6你可以使用 开放的方法。awt.桌面 启动文件的默认使用的应用程序为目前的平台。

其他提示

不知道,如果这会帮助你多少...我用java1.5+'s ProcessBuilder 启动外壳中的脚本java程序。基本上,我做到以下几点:(尽管这可能不适用,因为你不想要捕捉的命令的输出;你实际上想要的文档-但是,也许这会引发一些东西,你可以使用的)

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) {}

这个问题可以是"开始"的命令均使用,而不是您的文件名称分析。例如,这似乎是工作以及在我WinXP机(在使用JAVA1.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();
        }
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top