怎么在 Java 中获取当前工作目录?

本教程将介绍如何在 Java 中获取当前工作目录?的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。

怎么在 Java 中获取当前工作目录? 教程 第1张

问题描述

I want to access my current working directory using Java.

My code:

 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);

Output:

Current dir: C:WINDOWSsystem32
Current dir using System: C:WINDOWSsystem32

My output is not correct because the C drive is not my current directory.

How to get the current directory?

解决方案

Code :

public class JavaApplication {
  public static void main(String[] args) {
 System.out.println("Working Directory = " + System.getProperty("user.dir"));
  }
}


Explanation:

From the documentation:

java.io package resolve relative pathnames using current user directory. The current directory is represented as system property, that is, user.dir and is the directory from where the JVM was invoked.

好了关于怎么在 Java 中获取当前工作目录?的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。