File File(String) in Java

File(String): This method is available in the java.io.File class of Java.

Syntax:

java.io.File.File(String pathname)

This method takes one argument. This method creates a new File instance by converting the given pathname string into an abstract pathname.

Note: If the given string is the empty string, then the result is the empty abstract pathname.

Parameters: One parameter is required for this method.

pathname: A pathname string.

Throws:

NullPointerException - If the pathname argument is null

Approach 1: When no exception

Java

import java.io.File;

public class Filepathname {
    public static void main(String[] args) {

        String pathname = "D:\\hello.txt";
        File file = new File(pathname);

        System.out.println(file);
    }
}

Output:

D:\hello.txt


Approach 2: NullPointerException 

Java

import java.io.File;

public class Filepathname {
    public static void main(String[] args) {

        String pathname = null;
        File file = new File(pathname);

        System.out.println(file);
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/java.io.File.<init>(File.java:279)


No comments:

Post a Comment