English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Java

Contrôle de flux Java

Java tableau

Java orienté objet (I)

Java orienté objet (II)

Java orienté objet (III)

Gestion des exceptions Java

Java Liste (List)

Java Queue (file d'attente)

Java Map collection

Java Set collection

Java entrée/sortie (I/O)

Java Reader/Writer

Autres sujets Java

Obtenir le répertoire de travail actuel dans le programme Java

Comprehensive list of Java examples

Dans ce programme, vous apprendrez à obtenir le répertoire de travail actuel en Java.

Example1:obtenir le répertoire de travail actuel

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

When running the program, the output is:

Working Directory = C:\Users\Admin\Desktop\currDir

Dans le programme ci-dessus, nous utilisons la méthode getProperty() de System pour obtenir l'attribut user.dir du programme. Cela retournera le répertoire contenant notre projet Java.

Example2Using path to get the current working directory

import java.nio.file.Paths;
public class CurrDirectory {
    public static void main(String[] args) {
        String path = Paths.get("").toAbsolutePath().toString();
        System.out.println("Working Directory = "); + path);
    }
}

When running the program, the output is:

Working Directory = C:\Users\Admin\Desktop\currDir

In the above program, we use the Path's get() method to get the current path of the program. This will return to the relative path of the working directory.

Then, we use toAbsolutePath() to change the relative path to the absolute path. Since it returns a Path object, we need to use the toString() method to change it to a string

Comprehensive list of Java examples