Using the ClassLoader to access files in your classpath

Here is a quick tid-bit about how to access files in Java that are in your classpath. For example, suppose you have a text file that you want to parse and it is packaged in your jar. You can access it through the ClassLoader using either the method getResource(), that returns an instance of URL, or getResourceAsStream, that returns an instance of InputStream. Below is a simple coding example:

import java.util.Scanner;
public class ExampleFileLoader {
  public static void main (String args[]) {
    Scanner scan = new Scanner (ExampleFileLoader.class.getClassLoader().getResourceAsStream("test_file.txt"));
    while (scan.hasNextLine())
      System.out.println(scan.nextLine());
  }
}

Short URL for this post: http://tmblr.co/Zd8FQxE1CL-x