问题描述
我创建了一个插件。它需要从 res 文件夹访问 2 个文件。现在的诀窍是, res 文件夹不在插件内。例如,我在本地发布了插件,因此它现在可以在您创建的任何项目下的工具菜单中看到。我想要的是,我创建的任何新项目,都会在 res 文件夹中有 2 个文件 factory.json 和 groups.json,现在我的插件应该能够访问这些文件。我尝试了如下所示的不同方法,但总是失败,说“找不到文件”异常。如果有人能帮我解决这个问题。它的赞赏。谢谢。
private static File getFileFromresource(String fileName) throws URISyntaxException {
ClassLoader classLoader = Validator.class.getClassLoader();
URL resource = classLoader.getResource(fileName);
if (resource == null) {
throw new IllegalArgumentException("file not found! " + fileName);
} else {
// Failed if files have whitespaces or special characters
//return new File(resource.getFile());
return new File(resource.toURI());
}
}
private static InputStream getFileFromresourceAsstream(String fileName) {
// The class loader that loaded the class
ClassLoader classLoader = Validator.class.getClassLoader();
InputStream inputStream = classLoader.getResourceAsstream(fileName);
// the stream holding the file content
if (inputStream == null) {
throw new IllegalArgumentException("file not found! " + fileName);
} else {
return inputStream;
}
}
解决方法
那是整洁的部分,你没有。 每次创建新项目时都必须自己添加它们,因为 res 文件夹不是插件,而是 res 用于资源(假设您使用 res 作为资源)
尝试通过手动添加每个 factory.json 和 groups.json
InputStream IS = getClass().getResourceAsStream("/res/file name");
或
InputStream IS = getClass().getResourceAsStream("root/dir/file name");
您的插件已在本地发布,因此添加地址可能会有所帮助
如果仍然没有,请尝试将仅在 res 文件夹中包含 factory.json 和 groups.json 的干净项目保存为您的项目模板。这取决于您的 IDE,
Intelij IDEA -Jetbrain:https://www.jetbrains.com/help/idea/saving-project-as-template.html
NetBeans IDE -Apache:https://netbeans.apache.org/tutorials/nbm-filetemplates.html
根据我的经验,我为新项目创建了自己的 netbeans 模板