【问题标题】:file read inside class of project A and calling this class in project B在项目 A 的类中读取文件并在项目 B 中调用此类
【发布时间】:2014-09-24 05:33:44
【问题描述】:

我有 2 个项目。项目 A 和项目 B。

在项目 A 中,我有一个类 MyClass,它有一个方法说:readMyFile(),它从某个 xyz 路径读取文件。

现在我正在尝试从项目 B 中的一个类中调用 readMyFile()。我收到错误消息,指出尝试读取的文件不存在。

如何确保项目 A 中 MyClass 中的 readFile() 正在读取的文件在项目 B 中也可见?

【问题讨论】:

  • 创建 ProjectB 的 jar 并作为外部 jar 添加到 ProjectA。或者更好地使用maven 进行依赖管理。
  • 不要读取 File 的 jar 资源。如果这就是您正在做的事情,那可能是您的第一个问题。使用getClass().getResourceAsStream() 或其变体之一将其作为资源阅读。其次,我不会尝试使用依赖于 jar B 的路径直接从 A 读取文件。相反,只需在项目 B 中创建一个将提供其资源的类。只需从项目 A 中调用该类/方法

标签: java eclipse file filepath


【解决方案1】:

对扩展答案的评论:

不要读取 File 的 jar 资源。这可能是您的第一个问题,如果您正在这样做的话。使用getClass().getResourceAsStream() 或其变体之一将其作为资源(通过 URL)读取。其次,我不会尝试使用依赖于 jar B 的路径直接从 A 读取文件。相反,只需在项目 B 中创建一个将提供其资源的类。只需从项目 A 中调用该类/方法

例如

ProjectB
       src
          resources
                 images
                      background.png
                 text
                      stackoverflow.txt
          mypackage
                 ResourceFinder.java

ResourceFinder.java

public class ResourceFinder {
    public static final String BACKGROUND_IMG = "background.png";
    public static final Sting STACKOVERFLOW_TXT = "stackoverflow.txt";

    // maybe you'll want to do some try/catching null checks
    // I'm being lazy
    public static BufferedImage getImage(String fileName ) throws Exception {
        URL url = ResourceFinder.class.getResource("/images/" + fileName);
        BufferedImage image = ImageIO.read(url);
        return image;
    }

    public static InputStream getTextFile(String file) throws Exception {
        InputStream is = ResourceFinder.class.getResourceAsStream(
                                                        "/text/" + fileName);
        return is;
    }
}

然后在您的项目 A 中,您可以执行类似的操作

BufferedImage image = ResourceFinder.getImage(ResourceFinder.BACKROUND_IMG);

or

InputStream is = ResourceFinder.getTextFile(ResourceFinder.STACKOVERFLOW_TXT);
BufferedReader reader = new BufferedReader(new InputStreamReader(is);

请记住,当您使用File 或其任何FileXxx 变体时,您正在从文件系统中读取。因此,一旦文件“jarred”,您使用的任何硬编码路径都可能不起作用,因为位置不再相同。这就是为什么我们通过 URL 读取它,Class.getResource() 返回一个 URLClass.getResourceAsStream() 返回一个 InputStream,使用引擎盖下的 URL。还有其他使用ClassLoader 的变体。有关其他变体,请参阅 ClassClassLoader API。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-21
    • 2015-08-11
    • 2019-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多