7

Java プログラムでメモ帳を開きたいです。ボタンが 1 つあるとします。このボタンをクリックすると、メモ帳が表示されます。私はすでにファイル名とディレクトリを持っています。

このケースをどのように実装できますか?

4

7 に答える 7

21

試す

if (Desktop.isDesktopSupported()) {
    Desktop.getDesktop().edit(file);
} else {
    // I don't know, up to you to handle this
}

ファイルが存在することを確認してください。これを指摘してくれた Andreas_D に感謝します。

于 2010-08-15T11:49:52.583 に答える
10

(メモ帳で「myfile.txt」を開くと仮定します:)

ProcessBuilder pb = new ProcessBuilder("Notepad.exe", "myfile.txt");
pb.start();
于 2012-03-01T20:30:25.700 に答える
5

Windowsプログラムを起動したいと仮定するとnotepad.exe、関数を探していexecます。おそらく次のようなものを呼び出したいと思うでしょう:

Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("C:\\path\\to\\notepad.exe C:\\path\\to\\file.txt");

たとえば、私のマシンのメモ帳は次の場所にありC:\Windows\notepad.exeます。

Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("C:\\Windows\\notepad.exe C:\\test.txt");

これにより、ファイル test.txt が編集用に開かれたメモ帳が開きます。

実行元の作業ディレクトリである 3 番目のパラメータを指定することもできることに注意してください。execしたがって、プログラムの作業ディレクトリに関連して保存されているテキスト ファイルを起動できます。

于 2010-08-15T11:30:58.583 に答える
2
String fileName = "C:\\Users\\Riyasam\\Documents\\NetBeansProjects\\Student Project\\src\\studentproject\\resources\\RealWorld.chm";
        String[] commands = {"cmd", "/c", fileName};
        try {
            Runtime.getRuntime().exec(commands);
//Runtime.getRuntime().exec("C:\\Users\\Riyasam\\Documents\\NetBeansProjects\\SwingTest\\src\\Test\\RealWorld.chm");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
于 2012-05-13T03:33:34.793 に答える
2

IDE (Eclipse) では、 "C:\path\to\notepad.exe C:\path\to\file.txt" について説明します。だから私は私と私のIDEを幸せに保つために働く以下を使用しました:o)うまくいけば、これは他の人を助けるでしょう.

String fpath;
fPath =System.getProperty("java.io.tmpdir")+"filename1" +getDateTime()+".txt";
//SA - Below launches the generated file, via explorer then delete the file "fPath"
       try { 
        Runtime runtime = Runtime.getRuntime();         
        Process process = runtime.exec("explorer " + fPath);

Thread.sleep(500); //lets give the OS some time to open the file before deleting

    boolean success = (new File(fPath)).delete();
    if (!success) {
        System.out.println("failed to delete file :"+fPath);
        // Deletion failed
    }

} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace(); 
}
于 2011-11-16T09:35:22.930 に答える
2

SWTを使用すると、任意のウィンドウを起動できます。Windows でテキストのダブルクリックをエミュレートしたい場合は、プレーンな JRE だけでは不可能です。SWT などのネイティブ ライブラリを使用し、次のコードを使用してファイルを開くことができます。

    org.eclipse.swt.program.Program.launch("c:\path\to\file.txt")

サードパーティのライブラリを使用したくない場合は、notepad.exe がどこにあるか (または PATH に表示されているか) を知っておく必要があります。

    runtime.exec("notepad.exe c:\path\to\file.txt");

Apache common-execは、外部プロセスの実行を処理するための優れたライブラリです。

更新: あなたの質問に対するより完全な回答は、ここで見つけることができます

于 2010-08-15T11:33:44.113 に答える