Getting the Current Working Directory in Java
I want to access my current working directory using
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);
OutPut:
Current dir: C:WINDOWSsystem32
Current dir using System: C:WINDOWSsystem32
My output is not correct because C drive is not my current directory. Need help in this regard.
public class JavaApplication1 {
public static void main(String[] args) {
System.out.println("Working Directory = " +
System.getProperty("user.dir"));
}
}
这将从应用程序初始化的位置打印完整的绝对路径。
See: http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
Using java.nio.file.Path
and java.nio.file.Paths
, you can do the following to show what Java thinks is your current path. This for 7 and on, and uses NIO.
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current relative path is: " + s);
This outputs Current relative path is: /Users/george/NetBeansProjects/Tutorials
that in my case is where I ran the class from. Constructing paths in a relative way, by not using a leading separator to indicate you are constructing an absolute path, will use this relative path as the starting point.
以下工作在Java 7及更高版本上(请参阅此处以获取文档)。
import java.nio.file.Paths;
Paths.get(".").toAbsolutePath().normalize().toString();
链接地址: http://www.djcxy.com/p/36636.html
上一篇: 为什么Java的SimpleDateFormat不是线程
下一篇: 使用Java获取当前工作目录