如何在java中获取执行目录路径

Moh*_*han 17 java

我已经制作了一个纯Java应用程序,它告诉我给定目录中的文件数量.现在我使用以下代码设置当前目录:

`File f = new File(".");`
Run Code Online (Sandbox Code Playgroud)

之后我用它的jar文件安装了一个安装程序并将其安装在我的Windows 8中,然后我将它添加到windows右键单击下拉菜单(上下文菜单).当我从上下文菜单启动它时,它总是告诉我实际安装它的目录中的文件数,但是我想知道我执行它的目录的文件数.

所以请帮助我.我是这个领域的新手,我不想让你在当前目录和当前执行目录中混淆我.所以我写这么久,希望用非常简单的话来说清楚的答案.

谢谢

Gho*_*man 28

正如Jarrod Roberson在答案中所述:

一种方法是使用系统属性, System.getProperty("user.dir");这将为您提供"初始化属性时的当前工作目录".这可能就是你想要的.找到java命令的发布位置,在您的情况下,在包含要处理的文件的目录中,即使实际的.jar文件可能位于计算机上的其他位置.拥有实际.jar文件的目录在大多数情况下没有那么有用.

以下将打印出调用命令的当前目录,无论.class文件所在的.class或.jar文件位于何处.

public class Test
{
    public static void main(final String[] args)
    {
        final String dir = System.getProperty("user.dir");
        System.out.println("current dir = " + dir);
    }
}  
Run Code Online (Sandbox Code Playgroud)

如果您在,/User/me/并且您的.jar文件包含上面的代码将在/opt/some/nested/dir/命令中java -jar /opt/some/nested/dir/test.jar Test输出current dir = /User/me.

您还应该使用一个好的面向对象的命令行参数解析器.我强烈推荐JSAP,Java Simple Argument Parser.这将允许您使用 System.getProperty("user.dir"),或者传递其他内容来覆盖行为.一个更易于维护的解决方案.这将使得在目录中传递非常容易,并且user.dir如果没有传入任何内容,则能够重新开始.

示例:GetExecutionPath

import java.util.*;
import java.lang.*;

public class GetExecutionPath
{
  public static void main(String args[]) {
    try{
      String executionPath = System.getProperty("user.dir");
      System.out.print("Executing at =>"+executionPath.replace("\\", "/"));
    }catch (Exception e){
      System.out.println("Exception caught ="+e.getMessage());
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

以上输出就像

C:\javaexamples>javac GetExecutionPath.jav

C:\javaexamples>java GetExecutionPath
Executing at =>C:/javaexamples
Run Code Online (Sandbox Code Playgroud)

  • `System.getProperty("user.dir")`和`new File(".")`[通常返回相同的值](http://docs.oracle.com/javase/7/docs/api/java/ IO/File.html).那么为什么这会起作用,而`新文件(".")`却没有,根据这个问题? (2认同)

Kar*_*yan 6

以下可能对您有所帮助

  System.getProperty("user.dir")
Run Code Online (Sandbox Code Playgroud)

这将以字符串形式返回路径


sk2*_*212 6

你可以做一些疯狂的事情:

String absolute = getClass().getProtectionDomain().getCodeSource().getLocation().toExternalForm();
absolute = absolute.substring(0, absolute.length() - 1);
absolute = absolute.substring(0, absolute.lastIndexOf("/") + 1);
String configPath = absolute + "config/file.properties";
String os = System.getProperty("os.name");
if (os.indexOf("Windows") != -1) {
    configPath = configPath.replace("/", "\\\\");
    if (configPath.indexOf("file:\\\\") != -1) {
        configPath = configPath.replace("file:\\\\", "");
    }
} else if (configPath.indexOf("file:") != -1) {
    configPath = configPath.replace("file:", "");
}
Run Code Online (Sandbox Code Playgroud)

我用它来读出与执行路径相对的配置文件.您也可以使用它来获取jar文件的执行路径.