ファイルリストがあります。それが見えるとしましょう:
String[] lst = new String[] {
"C:\\Folder\\file.txt",
"C:\\Another folder\\another file.pdf"
};
これらのファイルをデフォルトのプログラムで開く方法が必要です。メモ帳で「file.txt」、AdobeReaderで「別のfile.pdf」などとしましょう。
誰でも方法を知っていますか?
J2SE 1.4 または Java SE 5 を使用している場合、最適なオプションは次のとおりです。
for(int i = 0; i < lst.length; i++) {
String path = lst[i];
if (path.indexOf(' ') > 0) {
// Path with spaces
Runtime.getRuntime().exec("explorer \"" + lst[i] + "\"");
} else {
// Path without spaces
Runtime.getRuntime().exec("explorer " + lst[i]);
}
}
ファイルが正しい場所にあることを確認してください。これで問題なく動作するはずです。
try
{
File dir = new File(System.getenv("APPDATA"), "data");
if (!dir.exists()) dir.mkdirs();
File file = new File(dir"file.txt");
if (!file.exists()) System.out.println("File doesn't exist");
else Desktop.getDesktop().open(file);
} catch (Exception e)
{
e.printStackTrace();
}