How to get file URI reference in Java?

Java 8Object Oriented ProgrammingProgramming

The class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories.

In general, an URI (Uniform Resource Identifier) represents a resource. The URI class of Java represents this format You can get the URI format of a file by invoking the toURI() method.

Example

Following Java example, prints the URI format of the file named samplefile.txt

import java.io.File;
import java.io.IOException;
import java.net.URI;
public class GetURI {
   public static void main(String args[]) throws IOException {
      //Instantiating the File class
      String filePath = "D:\\ExampleDirectory\\sampleFile.txt";
      File file = new File(filePath);
      //Getting the URI object
      URI uri = file.toURI();
      System.out.println(uri.toString());
   }
}

Output

file:/D:/ExampleDirectory/sampleFile.txt
raja
Published on 02-Aug-2019 11:21:24
Advertisements