Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux中的Java路径_Java_Linux_Path - Fatal编程技术网

Linux中的Java路径

Linux中的Java路径,java,linux,path,Java,Linux,Path,我有点问题,我似乎不明白是什么原因造成的。 我的项目中有一个文件夹,在这个文件夹中我有一个类,还有一个资源文件(在本例中是jasper report)。 但我可以访问文件的唯一方法是使用绝对路径或从项目根开始的某个路径 String path = "src/main/java/Views/LagerMain/lager.jrxml"; ^^这是可行的,我的类LagerController和lager.jrxml都在LagerMain文件夹下,但当我尝试这样做时: String path = "

我有点问题,我似乎不明白是什么原因造成的。 我的项目中有一个文件夹,在这个文件夹中我有一个类,还有一个资源文件(在本例中是jasper report)。 但我可以访问文件的唯一方法是使用绝对路径或从项目根开始的某个路径

String path = "src/main/java/Views/LagerMain/lager.jrxml";
^^这是可行的,我的类LagerController和lager.jrxml都在LagerMain文件夹下,但当我尝试这样做时:

String path = "lager.jrxml";
我有一个错误,文件找不到。 我试着用谷歌搜索这个,以便更好地理解它,但什么也没找到


一句话,为什么我不能从类访问我的文件,当它们都在同一个地方时,为什么相对路径不起作用。

如果主类位于不同的目录中,那么程序将尝试访问那里的
lager.jrxml
,而不是普通类的目录

对于常规类目录

String path = new String(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
.getPath() + System.getProperty("line.separator") + "lager.jrxml");
String path = new String(System.getProperty("user.dir")
 + System.getProperty("line.separator") + "lager.jrxml");
如果不起作用,请尝试以下方法:

// your directory
File f = new File("src");
File[] matchingFiles = f.listFiles(new FilenameFilter() {
    public boolean accept(File dir, String name) {
        return name.startsWith("lager") && name.endsWith("jrxml");
    }
});
如果有多个文件名为
lager.jrxml
,则此方法将返回这两个文件,并且需要使用
for
循环浏览它们。否则,您可以使用

String path = new String(matchingFiles[0].getAbsolutePath())
主类目录

String path = new String(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
.getPath() + System.getProperty("line.separator") + "lager.jrxml");
String path = new String(System.getProperty("user.dir")
 + System.getProperty("line.separator") + "lager.jrxml");