假设我有我的主要课程C:\Users\Justian\Documents\
。我怎样才能让我的程序显示它在C:\Users\Justian\Documents
?
硬编码不是一种选择——如果它被移动到另一个位置,它需要具有适应性。
我想将一堆 CSV 文件转储到一个文件夹中,让程序识别所有文件,然后加载数据并操作它们。我真的只想知道如何导航到该文件夹。
假设我有我的主要课程C:\Users\Justian\Documents\
。我怎样才能让我的程序显示它在C:\Users\Justian\Documents
?
硬编码不是一种选择——如果它被移动到另一个位置,它需要具有适应性。
我想将一堆 CSV 文件转储到一个文件夹中,让程序识别所有文件,然后加载数据并操作它们。我真的只想知道如何导航到该文件夹。
一种方法是使用系统属性 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
如果没有传递任何内容,则能够回退。
使用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());
}
}
根据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()
参数传递。
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,但它会删除诸如 ../../../
this.getClass().getClassLoader().getResource("").getPath()
如果要获取当前工作目录,请使用以下行
System.out.println(new File("").getAbsolutePath());
如果你想要当前源代码的绝对路径,我的建议是:
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));
我刚用过:
import java.nio.file.Path;
import java.nio.file.Paths;
...
Path workingDirectory=Paths.get(".").toAbsolutePath();
谁说你的主类在本地硬盘的文件中?类通常捆绑在 JAR 文件中,有时通过网络加载,甚至动态生成。
那么你真正想做的是什么?可能有一种方法可以不对类的来源做出假设。