获取Java中的当前工作目录 [英] Get current working directory in Java

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

问题描述

假设我的主要课程在C:\ Users \ Justian \Documents。

Let's say I have my main class in C:\Users\Justian\Documents.

如何让我的程序显示它在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文件转储到一个文件夹中,让程序识别所有文件,然后加载数据并操纵它们。我真的只是想知道如何导航到该文件夹​​。

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.

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

推荐答案

一种方法是使用< a href =http://java.sun.com/javase/6/docs/api/java/lang/System.html#getProperty%28java.lang.String%29 =noreferrer> system property System.getProperty(user.dir); 这将为您提供初始化属性时的当前工作目录。这可能是你想要的。找出 java 命令的发布位置,在您的情况下,在包含要处理的文件的目录中,即使实际的.jar文件可能位于计算机上的其他位置。拥有实际.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测试将输出当前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.

您还应该看一下使用一个好的面向对象命令行参数解析器。
我强烈推荐 JSAP ,Java Simple Argument Parser。这将允许您使用 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天全站免登陆