class

Find a file in classpath

In this example we shall show you how to find a file in the classpath. To find a file in the classpath we have created a method, File findFileOnClassPath(final String fileName) that reads a fileName and returns the File. The method is described below:

  • It uses the System.getProperty(String key) to find the classpath of java and the path separator used.
  • It creates a new StringTokenizer to parse the classpath, using the path separator as a delimiter.
  • It gets the tokens of the StringTokenizer, using hasMoreTokens() and nextToken() API methods of StringTokenizer.
  • For each token it creates a new File and the absolute form of this File pathname, using getAbsoluteFile() API method of File.
  • If the returned File is a normal File, with isFile() API method of File, it searches for the parent File, with getParent() API method of File and creates a new File from the parent pathname string and the given pathname string. If it exists it returns the File, else it returns the File created from the specified pathname and the given pathname,

as described in the code snippet below.


package com.javacodegeeks.snippets.core;


import java.io.File;
import java.util.StringTokenizer;

/**
 * A class containing useful utility methods relating to files.
 */
public class FileUtils {

    public static void main(String[] args){

  

  File classpathFile = findFileOnClassPath("<FILENAME TO FIND IN CLASSPATHS>");

  System.out.print(classpathFile.getName());

  
    }
    /**
     * Returns a reference to a file with the specified name that is located
     * somewhere on the classpath.
     */
    public static File findFileOnClassPath(final String fileName) {


  final String classpath = System.getProperty("java.class.path");

  final String pathSeparator = System.getProperty("path.separator");


  final StringTokenizer tokenizer = new StringTokenizer(classpath, pathSeparator);


  while (tokenizer.hasMoreTokens()) {





final String pathElement = tokenizer.nextToken();



final File directoryOrJar = new File(pathElement);


final File absoluteDirectoryOrJar = directoryOrJar.getAbsoluteFile();



if (absoluteDirectoryOrJar.isFile()) {


    final File target = new File(absoluteDirectoryOrJar.getParent(), fileName);


    if (target.exists()) {



  return target;


    }


} else {


    final File target = new File(directoryOrJar, fileName);


    if (target.exists()) {



  return target;


    }


}


  }

  return null;

    }
}

  
This was an example of how to find a file in the classpath in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button