假设我的主类在 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文件的目录并不那么有用。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 Simple Argument Parser。这将让您使用System.getProperty("user.dir")
,并且可以传入其他内容以覆盖默认行为。这是一种更可维护的解决方案。这将使传递要处理的目录变得非常容易,并且能够回退到user.dir
,如果没有传入任何内容。
user.dir
中当前工作目录的绝对路径,非常易于使用。只需调用System.getProperty("user.dir")即可。 - user2916050使用CodeSource#getLocation()
。这在JAR文件中也可以正常工作。您可以通过ProtectionDomain#getCodeSource()
获取CodeSource
,而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());
我刚刚使用了:
import java.nio.file.Path;
import java.nio.file.Paths;
...
Path workingDirectory=Paths.get(".").toAbsolutePath();
Paths.get("").toAbsolutePath()
。 - To KraPaths.get("my/file").toAbsolutePath()
,我会得到 /my/file
,这绝对不是当前工作目录。 - abergmeierString 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));
谁说你的主类一定在本地硬盘上的一个文件中?类通常被打包在JAR文件中,有时通过网络加载甚至动态生成。
那么你真正想要做什么?可能有一种方法可以做到这一点,而不会对类的来源作出假设。