Bài này hướng dẫn bạn 3 cách để có get thư mục hiện tại trong java:
- Get thư mục hiện tại trong java bằng việc sử dụng property “user.dir”.
- Get thư mục hiện tại trong java bằng việc sử dụng ClassName.class.getProtectionDomain().
- Get thư mục hiện tại trong java bằng việc sử dụng file.getAbsolutePath().
Nội dung chính
1. Sử dụng property "user.dir"
Example 1: Get thư mục hiện tại trong java bằng việc sử dụng phương thức getProperty() với đối số "user.dir".
package com.realtut;
public class GetCurrentDirExample1 {
    public static void main(String[] args) {
        String currentDirectory = System.getProperty("user.dir");
        System.out.println("current dir: " + currentDirectory);
    }
}
Kết quả:
current dir: D:\workspace\java-learn
2. Sử dụng ClassName.class.getProtectionDomain()
Example 2: Get thư mục hiện tại trong java bằng việc sử dụng phương thức ClassName.class.getProtectionDomain().getCodeSource().getLocation():
package com.realtut;
import java.io.File;
import java.net.URL;
public class GetCurrentDirExample2 {
    public static void main(String[] args) {
        URL location = GetCurrentDirExample1.class.getProtectionDomain()
                .getCodeSource().getLocation();
        File file = new File(location.getFile());
        System.out.println("current dir: " + file.getParent());
    }
}
Kết quả:
current dir: D:\workspace\java-learn
3. Sử dụng file.getAbsolutePath()
Example 3: Get thư mục hiện tại trong java bằng việc sử dụng phương thức file.getAbsolutePath():
package com.realtut;
import java.io.File;
public class GetCurrentDirExample3 {
    public static void main(String[] args) {
        File currentDirectory = new File("");
        System.out.println("current dir: " + currentDirectory.getAbsolutePath());
    }
}
Kết quả:
current dir: D:\workspace\java-learn
 
                      