从Java中打开文档的更好方法是什么?

3
我一直在使用以下代码来打开Office文档、PDF等文件,它在我的Windows机器上使用Java运行良好,除了当文件名中有多个连续空格时(例如"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会抱怨找不到该文件。但是...当我直接从命令行运行命令时,它可以正常运行。
3个回答

5

0

不确定这是否能帮到您... 我使用 Java 1.5+ 的 ProcessBuilder 在 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) {}

0
问题可能是你使用的 "start" 命令,而不是文件名解析。例如,在我的 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();
        }
    }
}

请确认您正在使用C:\so\My[space][space]Doc.doc文件,是吗? - Allain Lalonde

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接