在 Java 中使用相对目录路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1131500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:06:21  来源:igfitidea点击:

Using relative directory path in Java

javafile

提问by

I am trying to use a relative path to locate an executable file within a Java class instead of hard-coded lines which worked, but using something like:

我正在尝试使用相对路径来定位 Java 类中的可执行文件,而不是有效的硬编码行,但使用以下内容:

final static String directory = "../../../ggla/samples/obj/linux_x86"

final static String directory = "../../../ggla/samples/obj/linux_x86"

fails... what is the proper way of using a relative path in Java?

失败......在Java中使用相对路径的正确方法是什么?

采纳答案by Yishai

The most likely explanation is that your current directory is not where you think that it is. You can inspect the system property of user.dir to see what the base path of the application is, or you can do something like this:

最可能的解释是您的当前目录不在您认为的位置。您可以检查 user.dir 的系统属性以查看应用程序的基本路径是什么,或者您可以执行以下操作:

 System.out.println(new File(".").getCanonicalPath());

right before you use that relative path to debug where your relative reference starts.

在您使用该相对路径调试相对引用开始的位置之前。

回答by sleske

You can use relative paths like you describe, and it should work. So the error is probably somewhere else.

您可以使用您描述的相对路径,它应该可以工作。所以错误可能在其他地方。

Please post a complete program to reproduce your error, then we may be able to help.

请发布一个完整的程序来重现您的错误,然后我们可能会提供帮助。

回答by Thomas Owens

I would start by using the separator and path separator specified in the Java File class. However, as I said in my comment, I need more info than "it fails" to be of help.

我将首先使用 Java File 类中指定的分隔符和路径分隔符。但是,正如我在评论中所说,我需要比“失败”更多的信息来提供帮助。

回答by Matthieu

For relative path, maybe you can use one of the method provide by java for the beginning of the relative path as getRelativePath.... You have to use / and not // in the String in java !

对于相对路径,也许您可​​以使用 java 提供的方法之一作为相对路径的开头作为 getRelativePath .... 您必须在 java 中的字符串中使用 / 而不是 // !

回答by Karl

Use System.out.println(System.getProperty("user.dir")); to see where your current directory is. You can then use relative paths from this address.

使用 System.out.println(System.getProperty("user.dir")); 查看您当前的目录在哪里。然后,您可以使用来自该地址的相对路径。

Alternatively if you dont need to update the file you are trying to read obtain it from the classpath using getResourceAsStream("filename");

或者,如果您不需要更新您尝试读取的文件,则使用 getResourceAsStream("filename"); 从类路径中获取它;

Karl

卡尔

回答by bruno conde

What you need is getCanonicalPathor getCanonicalFileto resolve the relative paths.

您需要的是getCanonicalPathgetCanonicalFile解决相对路径。

System.out.println(new File("../../../ggla/samples/obj/linux_x86")
    .getCanonicalPath());