我是否错误地访问了java中的这些资源文件?

时间:2014-11-20 05:13:54

标签: java eclipse path

我有两节课。一个是共同的库,另一个是从库中消费的客户端。

图书馆的结构如下:

public class Library
{



    public Library()
    {
         String pathToResourceA="src/main/resources/A.xls";// A.xls is present within resources
         String key="apples";

         Resource res= loadResourceBasedOnDoc(pathToResource,key);
         ...//process resource

    }

}

这是相应的测试类

public class LibraryTest
{
    @Test
    public void testLibrary()
    {
        new Library();// works as expected- the test passes and the resource is loaded.//ie. A.xls is found in the right place

    }

}

但是,当我尝试以下列方式从我的客户端访问库时

import packagename.Library

public class Client{

    Library lib;
    public Client()
    {
        lib= new Library();// throws a FileNotFoundException!

    }

}

我收到FileNotFoundException。我猜这与在A类中定义pathToResourceA的正确值有关,但无法弄清楚它是什么。任何想法将不胜感激。谢谢!

loadResourcesBasedonDoc的代码

protected Resource loadResourceBasedOnDoc(String filename,String password)
{
InputStream in = null;
        try {
            in = new FileInputStream(filename);
    //further in is processed...

1 个答案:

答案 0 :(得分:0)

问题是您使用的是相对文件路径:

String pathToResourceA="src/main/resources/A.xls";// A.xls is present within resources

然后在loadResourceBasedOnDoc方法中处理它,如下所示:

in = new FileInputStream(filename);

此调用在文件系统上查找文件(src / main / resources / A.xls)。由于路径是相对路径,因此它会在相对于当前工作目录的目录中查找该文件。在单元测试中,当前工作目录可能是启动测试的目录。假设这是项目的根,测试可能会在项目中的文件系统上找到A.xls。

要解决此问题,我建议在loadResourceBasedOnDoc中使用完整路径名,如下所示:

String programLaunchDir = System.getProperty("user.dir")
in = new FileInputStream(programLaunchDir + File.separator  + filename);

user.dir 系统属性应该是当前的工作目录。因此,如果您可以强制执行该程序是从该目录启动的,那么您已经完成了设置。否则,您可能希望将程序包装在将目录传递给程序的批处理文件或shell脚本中。