File getCanonicalPath() in Java

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

Syntax:

String java.io.File.getCanonicalPath() throws IOException

This method returns the canonical pathname string of this abstract pathname.

Note: A canonical pathname is both absolute and unique.

Parameters: NA

Returns: The canonical pathname string denoting the same file or directory as this abstract pathname.

Throws:

1. IOException - If an I/O error occurs, which is possible because the construction of the canonical pathname may require file system queries.

2. SecurityException - If a required system property value cannot be accessed, or if a security manager exists and its java.lang.SecurityManager.checkRead method denies read access to the file.

Approach

Java

import java.io.File;
import java.io.IOException;

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

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

        try {
            System.out.println(file.getCanonicalPath());
        } catch (IOException e) {

            System.out.println("Error occured");
        }
    }
}

Output:

D:\hello.txt


No comments:

Post a Comment