質問

次のコードを使用して、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 がファイルの検索についてエラーを出します。しかし...コマンドラインから直接コマンドラインを実行すると、問題なく実行されます。

役に立ちましたか?

解決

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

他のヒント

これがあまり役立つかどうかはわかりません...Java 1.5以降を使用しています プロセスビルダー 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) {}

問題は、ファイル名の解析ではなく、使用している「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();
        }
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top