如何在Java中获取当前工作目录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3153337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get current working directory in Java?
提问by Justian Meyer
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
?
假设我的主要课程在C:\Users\Justian\Documents\
. 我怎样才能让我的程序显示它在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.
我想在一个文件夹中转储一堆 CSV 文件,让程序识别所有文件,然后加载数据并操作它们。我真的只想知道如何导航到该文件夹。
采纳答案by BalusC
One way would be to use the system propertySystem.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.
一种方法是使用系统属性,System.getProperty("user.dir");
这将为您提供“初始化属性时的当前工作目录”。这可能就是你想要的。找出java
发出命令的位置,在您的情况下是在包含要处理的文件的目录中,即使实际的 .jar 文件可能驻留在机器上的其他位置。在大多数情况下,拥有实际 .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.
以下内容将打印出调用命令的当前目录,无论 .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);
}
}
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
.
如果您在/User/me/
并且包含上述代码的 .jar 文件在/opt/some/nested/dir/
命令中,java -jar /opt/some/nested/dir/test.jar Test
则将输出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.
作为奖励,您还应该使用一个好的面向对象的命令行参数解析器。我强烈推荐JSAP,Java 简单参数解析器。这将使您可以使用System.getProperty("user.dir")
并或者传入其他内容来覆盖该行为。一个更易于维护的解决方案。这将使传入要处理的目录变得非常容易,并且user.dir
如果没有传入任何内容,则可以回退。
回答by Michael Borgwardt
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.
谁说你的主类在本地硬盘上的文件中?类通常捆绑在 JAR 文件中,有时通过网络加载,甚至动态生成。
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.
那么你真正想做的是什么呢?可能有一种方法可以不假设类的来源。
回答by BalusC
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()
.
使用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());
}
}
Updateas per the comment of the OP:
根据 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.
我想在一个文件夹中转储一堆 CSV 文件,让程序识别所有文件,然后加载数据并操作它们。我真的只想知道如何导航到该文件夹。
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()
这需要硬编码/知道它们在程序中的相对路径。而是考虑将其路径添加到类路径中,以便您可以使用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.
或者将其路径作为main()
参数传递。
回答by cyber-monk
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 ../../../
请注意,File.getCanonicalPath()
抛出一个已检查的 IOException 但它会删除诸如 ../../../
回答by Peter De Winter
this.getClass().getClassLoader().getResource("").getPath()
回答by jmamatos
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));
回答by user3696181
I just used:
我刚用过:
import java.nio.file.Path;
import java.nio.file.Paths;
...
...
Path workingDirectory=Paths.get(".").toAbsolutePath();
回答by rjrajsaha
If you want to get your current working directory then use the following line
如果要获取当前工作目录,请使用以下行
System.out.println(new File("").getAbsolutePath());