Java File Directory: Get Parent Path

In Java, you can utilize the getParent() method of the File class to retrieve the directory where the file is located. An example is shown below:

import java.io.File;

public class Main {
    public static void main(String[] args) {
        File file = new File("C:/Users/username/Documents/example.txt");

        String directory = file.getParent();
        System.out.println("文件所在目录:" + directory);
    }
}

In the example above, a File object representing the file example.txt is first created, then the getParent() method is called to get the directory where the file is located, and the result is then printed out.

bannerAds