如何在Java中获取当前工作目录?

Jus*_*yer 110 java path working-directory

假设我有我的主要课程C:\Users\Justian\Documents\.如何让我的程序显示它在C:\Users\Justian\Documents

硬编码不是一种选择 - 如果它被移动到另一个位置,它需要适应.

我想将一堆CSV文件转储到一个文件夹中,让程序识别所有文件,然后加载数据并操纵它们.我真的只想知道如何导航到该文件夹​​.

小智 145

一种方法是使用系统属性, 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如果没有传入任何内容,则能够重新开始.


Bal*_*usC 73

使用CodeSource#getLocation().这在JAR文件中也可以正常工作.您可以获得CodeSource通过ProtectionDomain#getCodeSource()ProtectionDomain依次获得人Class#getProtectionDomain().

public class Test {
    public static void main(String... args) throws Exception {
        URL location = Test.class.getProtectionDomain().getCodeSource().getLocation();
        System.out.println(location.getFile());
    }
}
Run Code Online (Sandbox Code Playgroud)

根据OP的评论更新:

我想将一堆CSV文件转储到一个文件夹中,让程序识别所有文件,然后加载数据并操纵它们.我真的只想知道如何导航到该文件夹​​.

这需要硬编码/了解他们在程序中的相对路径.而是考虑将其路径添加到类路径以便您可以使用ClassLoader#getResource()

File classpathRoot = new File(classLoader.getResource("").getPath());
File[] csvFiles = classpathRoot.listFiles(new FilenameFilter() {
    @Override public boolean accept(File dir, String name) {
        return name.endsWith(".csv");
    }
});
Run Code Online (Sandbox Code Playgroud)

或者将其路径作为main()参数传递.

  • +1.这项工作有几个条件; 最重要的是你的"主类"是从文件系统加载的.在Java中,这种假设是错误的并不是特别不寻常.但是,如果您确定要从文件系统上的JAR加载您的类,则这是**方法有效. (3认同)

cyb*_*onk 31

File currentDirectory = new File(new File(".").getAbsolutePath());
System.out.println(currentDirectory.getCanonicalPath());
System.out.println(currentDirectory.getAbsolutePath());
Run Code Online (Sandbox Code Playgroud)

打印类似于:

/path/to/current/directory
/path/to/current/directory/.
Run Code Online (Sandbox Code Playgroud)

请注意,File.getCanonicalPath()抛出一个已检查的IOException,但它会删除像 ../../../

  • `文件currentDirectory =新文件("");`也在工作 (2认同)

Pet*_*ter 13

this.getClass().getClassLoader().getResource("").getPath()
Run Code Online (Sandbox Code Playgroud)


小智 6

如果要获取当前工作目录,请使用以下行

System.out.println(new File("").getAbsolutePath());
Run Code Online (Sandbox Code Playgroud)


小智 5

如果要当前源代码的绝对路径,我的建议是:

String internalPath = this.getClass().getName().replace(".", File.separator);
String externalPath = System.getProperty("user.dir")+File.separator+"src";
String workDir = externalPath+File.separator+internalPath.substring(0, internalPath.lastIndexOf(File.separator));
Run Code Online (Sandbox Code Playgroud)


小智 5

我刚用过:

import java.nio.file.Path;
import java.nio.file.Paths;
Run Code Online (Sandbox Code Playgroud)

...

Path workingDirectory=Paths.get(".").toAbsolutePath();
Run Code Online (Sandbox Code Playgroud)

  • 你的不工作,这是正确的`Paths.get("").toAbsolutePath();` (7认同)