java - 如何将类设置为始终在其自己的项目文件夹中搜索给定路径?

标签 java eclipse path resources dependencies

这是问题的后续内容 How do I appropriately put and use project resources with a built jar?

我们再次进行设置:

  • 项目 A 具有
    • 项目根目录中包含 xml 架构的资源文件夹
    • 此项目中的一个类,在 xml 验证期间使用架构
      • 此类使用相对路径“resources”+ File.separator + SCHEMA-NAME
  • 另一个项目 B 依赖于项目 A
    • 它使用上面的类
    • 没有资源文件夹

当我运行项目 B 时,Eclipse 提示在指定的路径中找不到文件,因为它使用项目 A 类的路径在项目 B 的根文件夹内查找。如何将类设置为始终在其自己的项目文件夹中查找?

此设置的最佳实践是什么?这是正常使用吗?我是否需要将项目 A 作为项目 B 的 jar 提供?

最佳答案

如果您想访问与您的类位于同一包中的资源,您可以这样做

YourClass.class.getResourceAsStream("path/to/other/resource");

前面没有/,因为该路径是相对于类YourClass的包的。 Class#getResource(String) 的 javadoc 对此进行了解释

Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:

If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'. Otherwise, the absolute name is of the following form: modified_package_name/name

Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').

例如,对于完全限定的类com.mycompany.business.YourClass,它的类路径将显示在

classpath-root/
    schemas.xsd // some resource
    com/
        /mycompany
            /business
                YourClass.class // your class
                /schemas
                    your-class-schema.xsd // some resource

您将访问 your-class-schema.xsd 作为

YourClass.class.getResourceAsStream("schemas/your-class-schema.xsd");

您将访问 schemas.xsd 作为

YourClass.class.getResourceAsStream("/schemas.xsd");

如果项目A依赖于项目B,则A的类路径包括B的所有类文件和资源。

classpath-root-A/
    /com
        /project
            /a
                /classes
    /com
        /project
            /B
                /classes

您将应用相同的逻辑来访问“导入的”B 项目中的资源。您可以将 B 作为 jar 提供给 A 的类路径。当您这样做时,类路径将按照上面的示例进行解析。

关于java - 如何将类设置为始终在其自己的项目文件夹中搜索给定路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18575624/

相关文章:

java - Spring AuthenticationEntryPoint 返回 Tomcat HTML 错误而不是 JSON

java - 避免@Secured 注解的重复值

java - 使用 printwriter 时删除新行

java - eclipse:抛出异常时中断,在finally block 之前

Eclipse 类型...的层次结构与@Configurable注解不一致

Android:如何获取可绘制图像名称

python - PyCharm 模块名称冲突

java - Spring MVC : processing values from timesheet - multiple objects

java - Eclipse 'Installing Software' - chmod 失败

WordPress - 为什么我的自定义帖子无法通过 SEO 路径访问