gpt4 book ai didi

Linux 中的 Java 路径

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:40:12 24 4
gpt4 key购买 nike

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

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");

如果还是不行,试试这个:

// 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(System.getProperty("user.dir")
+ System.getProperty("line.separator") + "lager.jrxml");

关于Linux 中的 Java 路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43668530/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com