假设我的主类在C:\Users\Justian\Documents\
中。如何让我的程序显示它是C:\Users\Justian\Documents
格式的
硬编码不是一个选项-如果它被移动到另一个位置,它需要具有适应性。
我想把一堆CSV文件放在一个文件夹里,让程序识别所有的文件,然后加载数据并对它们进行操作。我真的只想知道如何导航到那个文件夹。
发布于 2010-07-01 05:12:00
一种方法是使用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
。
作为奖励,您还应该考虑使用好的面向对象的命令行参数解析器。我强烈推荐JSAP,这是一个Java简单参数解析器。这将允许您使用System.getProperty("user.dir")
,或者传入其他东西来覆盖该行为。一个更易维护的解决方案。这将使传入要处理的目录变得非常容易,并且如果没有传入任何内容,则可以退回到user.dir
。
发布于 2010-07-01 05:06:32
使用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());
}
}
根据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()
参数传递。
发布于 2012-06-05 22:58:00
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,但它会删除../../../
等内容
https://stackoverflow.com/questions/3153337
复制相似问题