我正在尝试从我的项目文件夹中获取文件(readme.txt)。不知道如何获得项目的位置。当我说项目时,我指的是我的应用程序代码编写的位置,而不是运行时应用程序。我试过获取绝对路径,相对路径...它总是给我一个运行时应用程序的文件夹。我还尝试了像this.getClass()这样的东西,并尝试提取path或System.getProperty("user.dir")。这两个还提供了我的eclipse.../.../...运行时应用程序的路径。我正在制作eclipse插件,这个文件应该是我的插件的一部分,这样当用户点击按钮时,这个文件就会打开(它是一些帮助txt文件)。这是我打开文件的代码,问题是路径。
/**
* Help button listener. If button is pressed, help file is opened.
*/
private void listenButtonHelp() {
buttonHelp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (Desktop.isDesktopSupported()) {
File helpFile = new File("\\readme.txt");
helpFile.setReadOnly();
Desktop desktop = Desktop.getDesktop();
try {
desktop.open(helpFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}发布于 2018-05-28 16:32:13
这取决于文件在项目中的确切位置。一个干净的位置可能是${project.root}/resources,所以创建一个文件夹并将文件放在那里。将其标记为Eclipse中的“源文件夹”(项目属性、->构建路径、->源文件夹)。您当前的设置不是一个好主意,因为Eclipse的编译不会将该文件包含在您的发行版中。
现在,当您编译代码时,这将被复制到目标控制器(默认情况下为bin);您可以在文件浏览器中打开它进行检查。
因此,要检查该文件是否存在,您可以执行以下操作
Path filePath = Paths.get("resources", "readme.txt");
System.out.println(Files.exists(filePath));如果你需要它作为一个File,你可以这样做
File readmeFile = filePath.toFile();这将从源项目文件夹中读取文件,因此在其他地方运行该程序后,该文件将不会有太大用处。
为此,您可以使用ClassLoader
URL readmeUrl = ClassLoader.getSystemClassLoader().getResource("resources/readme.txt"));
File readmeFile = new File(readmeUrl.getFile());发布于 2018-05-29 16:01:52
我找到了答案,这对我很有效:
/**
* Help button listener. If button is pressed, help file is opened.
*/
private void listenButtonHelp() {
buttonHelp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (Desktop.isDesktopSupported()) {
File file = null;
Bundle bundle = Platform.getBundle("TestProject");
IPath path = new Path("resources/readme.txt");
URL url = FileLocator.find(bundle, path, null);
/*
* After FileLocator, I get also this, like I commented before:
* D:\\eclipse-rcp-oxygen\\eclipse\\..\\..\\..\\eclipse_oxygen_workspace\\
* TestProject\\resources\\readme.txt and before it didn't work but if
* you add these lines:
* url = FileLocator.toFileURL(url);
* file = URIUtil.toFile(URIUtil.toURI(url));
* Like in my try bracket, it works. I guess it needs to be
* converted using URIUtil.
* Now it finds file, and it can be opened, also works for .html files.
*/
Desktop desktop = Desktop.getDesktop();
try {
url = FileLocator.toFileURL(url);
file = URIUtil.toFile(URIUtil.toURI(url));
// file.setReadOnly();
desktop.open(file);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
});
}https://stackoverflow.com/questions/50561811
复制相似问题