问题
我想要使用我的当前工作目录
String current = new java.io.File( "." ).getCanonicalPath();
System.out.println("Current dir:"+current);
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盘不是我当前的目录。我需要帮助。
#1 热门回答(896 赞)
public class JavaApplication1 {
public static void main(String[] args) {
System.out.println("Working Directory = " +
System.getProperty("user.dir"));
}
}
这将从应用程序初始化的位置打印出完整的绝对路径。
#2 热门回答(301 赞)
请参阅:http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
使用java.nio.file.Path
和java.nio.file.Paths
,可以执行以下操作来显示你当前的路径。( JDK 7 及以上,使用NIO)。
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current relative path is: " + s);
这输出Current relative path is:/Users/george/NetBeansProjects/Tutorials
,在我的情况下是我运行类的地方。以相对方式构造路径,通过不使用前导分隔符来指示您正在构建绝对路径,将使用此相对路径作为起点。
#3 热门回答(195 赞)
以下工作在Java 7及更高版本(请参阅here以获得文档)。
import java.nio.file.Paths;
Paths.get(".").toAbsolutePath().normalize().toString();