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

发布于 2024-09-07 08:24:01 字数 231 浏览 2 评论 0 原文

假设我的主类位于 C:\Users\Justian\Documents\ 中。如何让我的程序显示它位于 C:\Users\Justian\Documents 中?

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

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

Let's say I have my main class in C:\Users\Justian\Documents\. How can I get my program to show that it's in C:\Users\Justian\Documents?

Hard-Coding is not an option- it needs to be adaptable if it's moved to another location.

I want to dump a bunch of CSV files in a folder, have the program recognize all the files, then load the data and manipulate them. I really just want to know how to navigate to that folder.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

上课铃就是安魂曲 2024-09-14 08:24:01

一种方法是使用 系统属性 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);
    }
}  

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

作为奖励,您还应该考虑使用良好的面向对象命令行参数解析器。
我强烈推荐 JSAP,Java 简单参数解析器。这将允许您使用 System.getProperty("user.dir") ,或者传递其他内容来覆盖该行为。一个更易于维护的解决方案。这将使传入要处理的目录变得非常容易,并且如果没有传入任何内容,则能够依靠 user.dir

One way would be to use the system property System.getProperty("user.dir"); this will give you "The current working directory when the properties were initialized". This is probably what you want. to find out where the java command was issued, in your case in the directory with the files to process, even though the actual .jar file might reside somewhere else on the machine. Having the directory of the actual .jar file isn't that useful in most cases.

The following will print out the current directory from where the command was invoked regardless where the .class or .jar file the .class file is in.

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

if you are in /User/me/ and your .jar file containing the above code is in /opt/some/nested/dir/
the command java -jar /opt/some/nested/dir/test.jar Test will output current dir = /User/me.

You should also as a bonus look at using a good object oriented command line argument parser.
I highly recommend JSAP, the Java Simple Argument Parser. This would let you use System.getProperty("user.dir") and alternatively pass in something else to over-ride the behavior. A much more maintainable solution. This would make passing in the directory to process very easy to do, and be able to fall back on user.dir if nothing was passed in.

思慕 2024-09-14 08:24:01

使用 CodeSource#getLocation ()。这在 JAR 文件中也能正常工作。您可以通过 CodeSource ="noreferrer">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());
    }
}

根据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");
    }
});

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

Use CodeSource#getLocation(). This works fine in JAR files as well. You can obtain CodeSource by ProtectionDomain#getCodeSource() and the ProtectionDomain in turn can be obtained by 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());
    }
}

Update as per the comment of the OP:

I want to dump a bunch of CSV files in a folder, have the program recognize all the files, then load the data and manipulate them. I really just want to know how to navigate to that folder.

That would require hardcoding/knowing their relative path in your program. Rather consider adding its path to the classpath so that you can use 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");
    }
});

Or to pass its path as main() argument.

绝不放开 2024-09-14 08:24:01
File currentDirectory = new File(new File(".").getAbsolutePath());
System.out.println(currentDirectory.getCanonicalPath());
System.out.println(currentDirectory.getAbsolutePath());

打印如下内容:

/path/to/current/directory
/path/to/current/directory/.

请注意,File.getCanonicalPath() 会抛出一个已检查的 IOException,但它将删除诸如 ../../../ 之类的内容

File currentDirectory = new File(new File(".").getAbsolutePath());
System.out.println(currentDirectory.getCanonicalPath());
System.out.println(currentDirectory.getAbsolutePath());

Prints something like:

/path/to/current/directory
/path/to/current/directory/.

Note that File.getCanonicalPath() throws a checked IOException but it will remove things like ../../../

旧梦荧光笔 2024-09-14 08:24:01
this.getClass().getClassLoader().getResource("").getPath()
this.getClass().getClassLoader().getResource("").getPath()
少年亿悲伤 2024-09-14 08:24:01

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

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

If you want to get your current working directory then use the following line

System.out.println(new File("").getAbsolutePath());
纵山崖 2024-09-14 08:24:01

我刚刚用过:

import java.nio.file.Path;
import java.nio.file.Paths;

...

Path workingDirectory=Paths.get(".").toAbsolutePath();

I just used:

import java.nio.file.Path;
import java.nio.file.Paths;

...

Path workingDirectory=Paths.get(".").toAbsolutePath();
风月客 2024-09-14 08:24:01

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

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

If you want the absolute path of the current source code, my suggestion is:

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));
完美的未来在梦里 2024-09-14 08:24:01

谁说你的主类位于本地硬盘上的文件中?类通常捆绑在 JAR 文件中,有时通过网络加载,甚至动态生成。

那么你真正想做的是什么?可能有一种方法可以做到这一点,而无需假设类的来源。

Who says your main class is in a file on a local harddisk? Classes are more often bundled inside JAR files, and sometimes loaded over the network or even generated on the fly.

So what is it that you actually want to do? There is probably a way to do it that does not make assumptions about where classes come from.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文