如何在Java中获取当前的工作目录? [英] How to get current working directory in Java?

查看:111
本文介绍了如何在Java中获取当前的工作目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的主要课程在C:\Users\Justian\Documents\中.我怎样才能让我的程序显示它在C:\Users\Justian\Documents中?

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.

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

推荐答案

一种方法是使用,这将为您提供初始化属性时的当前工作目录".这可能就是您想要的.即使实际的.jar文件可能位于计算机上的其他位置,也可以查找发出java命令的位置(在您的情况下,该目录中包含要处理的文件).在大多数情况下,拥有实际的.jar文件的目录并不是很有用.

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.

以下内容将打印出从中调用命令的当前目录,无论.class文件位于.class或.jar文件中.

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

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

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.

您还应该额外注意使用一个好的面向对象的命令行参数解析器. 我强烈建议使用Java简单参数解析器 JSAP .这将使您可以使用System.getProperty("user.dir"),也可以传入其他内容来替代行为.一个更加可维护的解决方案.这将使传递目录来进行处理非常容易,并且如果没有传递任何内容,也可以使用user.dir来结束.

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.

这篇关于如何在Java中获取当前的工作目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆