假设我的主要课程在C:\Users\Justian\Documents\
。如何让我的程序显示它在C:\Users\Justian\Documents
?
硬编码不是一种选择 - 如果它被移动到另一个位置,它需要具有适应性。
我想将一堆CSV文件转储到一个文件夹中,让程序识别所有文件,然后加载数据并对其进行操作。我真的只想知道如何导航到该文件夹。
答案 0 :(得分:139)
一种方法是使用system property 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
。
您还应该考虑使用一个好的面向对象的命令行参数解析器。
我强烈推荐Java {3}},Java Simple Argument Parser。这将允许您使用System.getProperty("user.dir")
,或者传递其他内容来覆盖行为。一个更易于维护的解决方案。这将使得在目录中传递非常容易,并且如果没有传入任何内容,则能够回到user.dir
。
答案 1 :(得分:71)
使用CodeSource#getLocation()
。这在JAR文件中也可以正常工作。您可以ProtectionDomain#getCodeSource()
获取CodeSource
,Class#getProtectionDomain()
可以获得ProtectionDomain
。
public class Test {
public static void main(String... args) throws Exception {
URL location = Test.class.getProtectionDomain().getCodeSource().getLocation();
System.out.println(location.getFile());
}
}
更新:
我想将一堆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()
参数传递。
答案 2 :(得分:31)
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,但会删除../../../
答案 3 :(得分:12)
this.getClass().getClassLoader().getResource("").getPath()
答案 4 :(得分:5)
我刚刚使用过:
import java.nio.file.Path;
import java.nio.file.Paths;
...
Path workingDirectory=Paths.get(".").toAbsolutePath();
答案 5 :(得分:4)
如果你想要当前源代码的绝对路径,我的建议是:
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));
答案 6 :(得分:3)
谁说您的主要课程在本地硬盘上的文件中?类通常捆绑在JAR文件中,有时通过网络加载,甚至可以即时生成。
那么你真正想做的是什么?可能有一种方法可以做到这一点,不会对类的来源做出假设。
答案 7 :(得分:3)
如果您想获取当前的工作目录,请使用以下行
System.out.println(new File("").getAbsolutePath());