Java プログラムでメモ帳を開きたいです。ボタンが 1 つあるとします。このボタンをクリックすると、メモ帳が表示されます。私はすでにファイル名とディレクトリを持っています。
このケースをどのように実装できますか?
Java プログラムでメモ帳を開きたいです。ボタンが 1 つあるとします。このボタンをクリックすると、メモ帳が表示されます。私はすでにファイル名とディレクトリを持っています。
このケースをどのように実装できますか?
試す
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().edit(file);
} else {
// I don't know, up to you to handle this
}
ファイルが存在することを確認してください。これを指摘してくれた Andreas_D に感謝します。
(メモ帳で「myfile.txt」を開くと仮定します:)
ProcessBuilder pb = new ProcessBuilder("Notepad.exe", "myfile.txt");
pb.start();
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
したがって、プログラムの作業ディレクトリに関連して保存されているテキスト ファイルを起動できます。
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();
}
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();
}
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は、外部プロセスの実行を処理するための優れたライブラリです。
更新: あなたの質問に対するより完全な回答は、ここで見つけることができます