2

次のコードを使用して、Javaを使用してWindowsマシンで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);            
}

編集:私が誤ったファイルでそれを実行すると、ウィンドウはファイルを見つけることについて不平を言います。しかし...コマンドラインから直接コマンドラインを実行すると、問題なく実行されます。

4

3 に答える 3

5

Java 6 を使用している場合は、java.awt.Desktop の open メソッドを使用するだけで、現在のプラットフォームのデフォルト アプリケーションを使用してファイルを起動できます。

于 2008-09-10T18:36:43.727 に答える
0

これが大いに役立つかどうかはわかりません...私はJava1.5 +の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) {}
于 2008-09-10T18:52:49.803 に答える
0

問題は、ファイル名の解析ではなく、使用している「開始」コマンドである可能性があります。たとえば、これは私の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();
        }
    }
}
于 2008-09-10T19:09:38.857 に答える