【问题标题】:How to let plugin access file in resource folder of any project where it runs如何让插件访问它运行的任何项目的资源文件夹中的文件
【发布时间】:2021-10-03 03:18:12
【问题描述】:

我创建了一个插件。它需要从 res 文件夹中访问 2 个文件。现在这里的技巧是, res 文件夹不在插件中。例如,我已经在本地发布了插件,因此它现在可以在您创建的任何项目下的工具菜单中看到。我想要的是,我创建的任何新项目,它将在 res 文件夹中有 2 个文件 facility.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;
    }
}

【问题讨论】:

    标签: java intellij-idea intellij-plugin intellij-15


    【解决方案1】:

    那是整洁的部分,你不知道。 每次创建新项目时都必须自己添加它们,因为 res 文件夹不是插件,而是 res 用于资源(假设您使用 res 作为资源)

    尝试手动添加每个 facility.json 和 groups.json

    InputStream IS = getClass().getResourceAsStream("/res/file name");
    

    InputStream IS = getClass().getResourceAsStream("root/dir/file name");
    

    您的插件已在本地发布,因此添加地址可能会有所帮助

    如果仍然没有,请尝试将 res 文件夹中只有 facility.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 模板

    【讨论】:

    • 嘿,这个解决方案没有帮助。我试过了。感谢您的宝贵时间。
    猜你喜欢
    • 1970-01-01
    • 2012-06-16
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-25
    相关资源
    最近更新 更多