Java File getParent() method with examples

January 04, 2020 No comments Java IO Examples File getParent

1. Introduction

The getParent() method returns the name of the parent directory for specified File. If the path does not have any parent this method will return null. The method is very similar to getParentFile() but in this case we will get only the string representation of the parent folder, not the whole File object.

2. Method signature

public String getParent()

Parameters:

  • method does not take any parameter

Returns

  • String - the name of the parent directory or null if specified pathname does not have a parent

3. Examples

3.1. The program that prints the parent of specified File objects

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.getParent()); // /tmp

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

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

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

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

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

The output:

/tmp
/tmp/frontbackend
/tmp
/
null

4. Conclusion

In this short article, we presented File.getParent() with a simple example of how to use this method. We can use this method to retrieve the parent name of the directory up to the root folder.

{{ message }}

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