Bài 206: Get thư mục hiện tại trong Java

Ngày đăng: 1/6/2023 10:03:47 AM

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().

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".

1

2

3

4

5

6

7

8      

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:workspacejava-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():

1

2

3

4

5

6

7

8

9

10

11

12

13    

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:workspacejava-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():

1

2

3

4

5

6

7

8

9

10       

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:workspacejava-learn

Nguồn tin: viettuts.vn