在Ubuntu(Linux)上使用Java从Desktop.open()打开路径 [英] Open a path with Desktop.open() from java on ubuntu (linux)
问题描述
从我用Java编写的应用程序中,我想使用操作系统文件浏览器打开一个文件夹.
From my application written in java I want to open a folder, using the operating system file explorer.
我使用Desktop.open(新文件(路径))
I use Desktop.open(new File(path))
这在Windows上可以正常工作,但在ubuntu 11.10(linux)上则无法使用.使用Desktop.open打开文件确实可以在ubuntu和Windows上正常工作.
This works fine on windows, but on ubuntu 11.10 (linux) it doesn't work. Using the Desktop.open to open a file does work, both on ubuntu and windows.
在两者之间使用一个步骤:文件fPath =新文件(fPath)并使用fPath.exists()和fPath.isDirectory()进行测试都可以得出结论.
Using a step in between: File fPath=new File(fPath) and testing it with fPath.exists() and fPath.isDirectory() both gives true.
使用Desktop.open(new File(path))给我这个例外:
using the Desktop.open(new File(path)) gives me this exception:
java.io.IOException: Failed to show URI:file:/and/here/the/path/I/use/
at sun.awt.X11.XDesktopPeer.launch(Unknown Source)
at sun.awt.X11.XDesktopPeer.open(Unknown Source)
at java.awt.Desktop.open(Unknown Source)
我还不能在苹果计算机上对此进行测试,但是我希望Desktop.open(new File(path))与系统无关.....
I was not able to test this on an apple computer yet, but I hoped the Desktop.open(new File(path)) was system independent.....
顺便说一下,完整的代码:
by the way, the complete code:
Desktop desktop = null;
// Before more Desktop API is used, first check
// whether the API is supported by this particular
// virtual machine (VM) on this particular host.
if (!Desktop.isDesktopSupported()) {
// show Error
return;
}
desktop = Desktop.getDesktop();
String path = "here the path ";
// by the way: I use System.getProperty("file.separator") as file seperator
try {
File fPath=new File(path);
if(!fPath.exists()){
// show Error
return;
}
if(!fPath.isDirectory()){
// show Error
return;
}
desktop.open(new File(path));
} catch (IOException e) {
log.severe(e.getMessage());
e.printStackTrace();
// show Error
return;
}
一些额外的信息:操作系统:Linux(3.0.0-16-generic-amd64)
Some extra information: OS: Linux (3.0.0-16-generic - amd64)
Java:1.6.0_30-b12
Java: 1.6.0_30-b12
Java主页:/opt/java/64/jre1.6.0_30
Java home: /opt/java/64/jre1.6.0_30
推荐答案
我遇到了同样的问题.但就我而言,它是Ubuntu 18.04和Java 1.8.0_161-b12在Windows 10中,一切正常.但是在Ubuntu上
I had the same problem. But in my case it was Ubuntu 18.04 and java 1.8.0_161-b12 In Windows 10, everything is working fine. But on Ubuntu
Desktop.getDesktop().open(new file)
程序停止响应.我决定将调用包装在执行程序中:
the program stopped responding. I decided to wrap the call in the executor:
private ExecutorService executorService;
BasicThreadFactory factory = new BasicThreadFactory.Builder()
.namingPattern("YourPatternIndeficator")
.build();
executorService = Executors.newSingleThreadExecutor(factory);
if (Desktop.isDesktopSupported()) {
File myFile = new File(path);
executorService.execute(() -> {
try {
Desktop.getDesktop().open(myFile);
} catch (IOException e) {
e.printStackTrace();
}
});
}
这篇关于在Ubuntu(Linux)上使用Java从Desktop.open()打开路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!