我想使用Java访问我当前的工作目录。
我的代码:
String currentPath = new java.io.File(".").getCanonicalPath();
System.out.println("Current dir:" + currentPath);
String currentDir = System.getProperty("user.dir");
System.out.println("Current dir using System:" + currentDir);输出:
Current dir: C:\WINDOWS\system32
Current dir using System: C:\WINDOWS\system32我的输出不正确,因为C盘不是我的当前目录。
如何获取当前目录?
发布于 2011-09-30 05:12:34
代码:
public class JavaApplication {
public static void main(String[] args) {
System.out.println("Working Directory = " + System.getProperty("user.dir"));
}
}这将打印当前目录的绝对路径,您的应用程序是从该目录初始化的。
说明:
java.io包使用当前用户目录解析相对路径名。当前目录表示为系统属性,即user.dir,并且是从中调用JVM的目录。
发布于 2013-04-12 01:10:26
请参阅:Path Operations (The Java™ Tutorials > Essential Classes > Basic I/O)
使用java.nio.file.Path和java.nio.file.Paths,您可以执行以下操作来显示您认为的当前路径。这适用于7及更高版本,并使用NIO。
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current absolute path is: " + s);这将输出以下内容:
Current absolute path is: /Users/george/NetBeansProjects/Tutorials在我的例子中,这就是我运行类的地方。
以相对方式构建路径,通过不使用前导分隔符来指示您正在构建绝对路径,将使用此相对路径作为起点。
发布于 2014-03-12 20:03:01
以下代码适用于Java7及更高版本(有关文档,请参阅here )。
import java.nio.file.Paths;
Paths.get(".").toAbsolutePath().normalize().toString();https://stackoverflow.com/questions/4871051
复制相似问题