Monday, December 29, 2014

Getting a File reference from Classpath

Sometime we need to get a file handle to a file sitting in classpath. This could be a configuration file or a properties file. To do that following code can be used to fetch the file handle

public class ReadingFileFromClasspath {

public static void main(String args[]) throws URISyntaxException     {
// Get the URL from the classpath to the file. 
 //Note the leading /
 //Assumes a.txt file at the given location
URL url = ReadingFileFromClasspath.class
System.out.println("URL is: " + url);

// URI is gloabl than URL. 
        //URL is a subset of URI. Check RFC 3986
URI uri = url.toURI();
System.out.println("URI is: " + uri);

// Get the file pointer using URI
File file = new File(uri);

        //Alternatively you can get the file path as string also.
//With this use the File constructor with String
//String filePath = url.getFile();
//File file = new File(filePath);

System.out.println("File is " + file);


No comments:

Post a Comment