Java File getParentFile() method with examples

January 04, 2020 No comments Java IO Examples File getParentFile

1. Introduction

The getParentFile() method returns the File representation of parent directory if given file have a parent. The method returns null for the root directories in Unix OS /, in Windows \\.

2. Method signature

public File getParentFile()

Parameters:

  • method does not take any parameter

Returns

  • File - the File instance of the parent directory, or null if given File does not have a parent

3. Examples

3.1. Program that prints parent directories using getParentFile() method:

package com.frontbackend.java.io.examples;

import java.io.File;

public class FrontBackend {

    public static void main(String args[]) {

        try {
            File file = new File("/tmp/frontbackend.txt");
            File dir3 = new File("/tmp/frontbackend/test");
            File dir2 = new File("/tmp/frontbackend");
            File tmp = new File("/tmp");
            File empty = new File("/");

            System.out.println(file.getParentFile()); // /tmp

            System.out.println(dir3.getParentFile()); // /tmp/frontbackend

            System.out.println(dir2.getParentFile()); // /tmp

            System.out.println(tmp.getParentFile()); // /

            System.out.println(empty.getParentFile()); // null

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The output:

/tmp
/tmp/frontbackend
/tmp
/
null

4. Conclusion

In this article, we presented File.getParentFile() method that returns the parent directory of given File instance. The method should be useful for most common operations on the filesystem in Java.

{{ message }}

{{ 'Comments are closed.' | trans }}