File File(URI) in Java

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

Syntax:

java.io.File.File(URI uri)

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

Note The exact form of a file: URI is system-dependent, hence the transformation performed by this constructor is also system-dependent.

Parameters: One parameter is required for this method.

uri: An absolute, hierarchical URI with a scheme equal to "file", a non-empty path component, and undefined authority, query, and fragment components

Throws:

1. NullPointerException - If uri is null.

2. IllegalArgumentException - If the preconditions on the parameter do not hold.

Approach 1: When no exception

Java

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;

public class FileUri {
    public static void main(String[] args)
throws URISyntaxException {

        URI uri = new URI("file:/D/hello");
        File file = new File(uri);

        System.out.println(file);
    }
}

Output:

\D\hello


Approach 2: NullPointerException 

Java

import java.io.File;
import java.net.URI;

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

        URI uri = null;
        File file = new File(uri);

        System.out.println(file);
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.net.URI.isAbsolute()" because "uri" is null at java.base/java.io.File.<init>(File.java:418)



Approach 3: IllegalArgumentException 

Java

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;

public class FileUri {
    public static void main(String[] args)
throws URISyntaxException {

        URI uri = new URI("/D/hello");
        File file = new File(uri);

        System.out.println(file);
    }
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: URI is not absolute at java.base/java.io.File.<init>(File.java:419)


No comments:

Post a Comment