Java find all files in package

Finding Files

If you have ever used a shell script, you have most likely used pattern matching to locate files. In fact, you have probably used it extensively. If you haven’t used it, pattern matching uses special characters to create a pattern and then file names can be compared against that pattern. For example, in most shell scripts, the asterisk, * , matches any number of characters. For example, the following command lists all the files in the current directory that end in .html :

The java.nio.file package provides programmatic support for this useful feature. Each file system implementation provides a PathMatcher . You can retrieve a file system’s PathMatcher by using the getPathMatcher(String) method in the FileSystem class. The following code snippet fetches the path matcher for the default file system:

String pattern = . ; PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);

The string argument passed to getPathMatcher specifies the syntax flavor and the pattern to be matched. This example specifies glob syntax. If you are unfamiliar with glob syntax, see What is a Glob.

Glob syntax is easy to use and flexible but, if you prefer, you can also use regular expressions, or regex, syntax. For further information about regex, see the Regular Expressions lesson. Some file system implementations might support other syntaxes.

If you want to use some other form of string-based pattern matching, you can create your own PathMatcher class. The examples in this page use glob syntax.

Once you have created your PathMatcher instance, you are ready to match files against it. The PathMatcher interface has a single method, matches , that takes a Path argument and returns a boolean: It either matches the pattern, or it does not. The following code snippet looks for files that end in .java or .class and prints those files to standard output:

PathMatcher matcher = FileSystems.getDefault().getPathMatcher(«glob:*.»); Path filename = . ; if (matcher.matches(filename))

Recursive Pattern Matching

Searching for files that match a particular pattern goes hand-in-hand with walking a file tree. How many times do you know a file is somewhere on the file system, but where? Or perhaps you need to find all files in a file tree that have a particular file extension.

The Find example does precisely that. Find is similar to the UNIX find utility, but has pared down functionally. You can extend this example to include other functionality. For example, the find utility supports the -prune flag to exclude an entire subtree from the search. You could implement that functionality by returning SKIP_SUBTREE in the preVisitDirectory method. To implement the -L option, which follows symbolic links, you could use the four-argument walkFileTree method and pass in the FOLLOW_LINKS enum (but make sure that you test for circular links in the visitFile method).

To run the Find application, use the following format:

Читайте также:  Login Form validation in HTML & CSS | CodingNepal

The pattern is placed inside quotation marks so any wildcards are not interpreted by the shell. For example:

Here is the source code for the Find example:

/** * Sample code that finds files that match the specified glob pattern. * For more information on what constitutes a glob pattern, see * https://docs.oracle.com/javase/tutorial/essential/io/fileOps.html#glob * * The file or directories that match the pattern are printed to * standard out. The number of matches is also printed. * * When executing this application, you must put the glob pattern * in quotes, so the shell will not expand any wild cards: * java Find . -name "*.java" */ import java.io.*; import java.nio.file.*; import java.nio.file.attribute.*; import static java.nio.file.FileVisitResult.*; import static java.nio.file.FileVisitOption.*; import java.util.*; public class Find < public static class Finder extends SimpleFileVisitor < private final PathMatcher matcher; private int numMatches = 0; Finder(String pattern) < matcher = FileSystems.getDefault() .getPathMatcher("glob:" + pattern); >// Compares the glob pattern against // the file or directory name. void find(Path file) < Path name = file.getFileName(); if (name != null && matcher.matches(name)) < numMatches++; System.out.println(file); >> // Prints the total number of // matches to standard out. void done() < System.out.println("Matched: " + numMatches); >// Invoke the pattern matching // method on each file. @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) < find(file); return CONTINUE; >// Invoke the pattern matching // method on each directory. @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) < find(dir); return CONTINUE; >@Override public FileVisitResult visitFileFailed(Path file, IOException exc) < System.err.println(exc); return CONTINUE; >> static void usage() < System.err.println("java Find " + " -name \"\""); System.exit(-1); > public static void main(String[] args) throws IOException < if (args.length < 3 || !args[1].equals("-name")) usage(); Path startingDir = Paths.get(args[0]); String pattern = args[2]; Finder finder = new Finder(pattern); Files.walkFileTree(startingDir, finder); finder.done(); >>

Recursively walking a file tree is covered in Walking the File Tree.

Источник

Getting all Class Files within a Particular Java Package: A Guide

There are various methods available on Stack Overflow and other websites to locate all the classes in a particular Java package. This technique can be extremely beneficial when it comes to scanning the class path.

How can I get all Class files in a specific package in Java?

On various platforms, including SO, I have come across many ways and inquiries regarding identifying all classes in a certain Java package. However, most of the provided solutions did not work for me and were inconsistent, such as functioning for Jar files but not ordinary Java projects in a folder, or vice versa. As a result, I combined all of the code snippets and created a solution that will operate seamlessly (for me) on both Jar files and plain folder arrangements.

Читайте также:  Form post in php example

By providing the name of the package to examine, the method getClassesInPackage can retrieve a complete list of classes within it. At present, there is no systematic handling of any exceptions that may arise.

Enjoy the code and have a good time experimenting with it!

public static final List> getClassesInPackage(String packageName) < String path = packageName.replaceAll("\\.", File.separator); List> classes = new ArrayList<>(); String[] classPathEntries = System.getProperty("java.class.path").split( System.getProperty("path.separator") ); String name; for (String classpathEntry : classPathEntries) < if (classpathEntry.endsWith(".jar")) < File jar = new File(classpathEntry); try < JarInputStream is = new JarInputStream(new FileInputStream(jar)); JarEntry entry; while((entry = is.getNextJarEntry()) != null) < name = entry.getName(); if (name.endsWith(".class")) < if (name.contains(path) && name.endsWith(".class")) < String classPath = name.substring(0, entry.getName().length() - 6); classPath = classPath.replaceAll("[\\|/]", "."); classes.add(Class.forName(classPath)); >> > > catch (Exception ex) < // Silence is gold >> else < try < File base = new File(classpathEntry + File.separatorChar + path); for (File file : base.listFiles()) < name = file.getName(); if (name.endsWith(".class")) < name = name.substring(0, name.length() - 6); classes.add(Class.forName(packageName + "." + name)); >> > catch (Exception ex) < // Silence is gold >> > return classes; > 

This is the response provided by @mythbu using the programming language Kotlin.

@Throws(Exception::class) fun getClassesInPackage(packageName: String) = with(packageName.replace(".", File.separator)) < System.getProperty("java.class.path") .split(System.getProperty("path.separator").toRegex()) .flatMap < classpathEntry ->if (classpathEntry.endsWith(".jar")) < JarInputStream(FileInputStream(File(classpathEntry))).use < s ->generateSequence < s.nextJarEntry >.map < it.name >.filter < this in it && it.endsWith(".class") >.map < it.substring(0, it.length - 6) >.map < it.replace('|', '.').replace('/', '.') >.map < Class.forName(it) >.toList() > > else < File(classpathEntry, this).list() ?.asSequence() ?.filter < it.endsWith(".class") >?.map < it.substring(0, it.length - 6) >?.map < Class.forName("$packageName.$it") >?.toList() ?: emptyList() > > > 

I want to find classes that implement a specific interface using spring, I'm afraid it is not possible for a native image to discover classes at runtime. Unlike JVM, a native image cannot load classes from jars or .

Reflections Library to Find All Classes within a Package

In one of our projects, I utilized the Fast Classpath Scanner and discovered it to be highly beneficial due to its numerous features for class path scanning. For instance, it can provide details on classes within a package, even if they are part of a third-party JAR, by conducting a thorough scan.

public Set> reflectPackage(String packageName) < final Set> classes = new HashSet<>(); new FastClasspathScanner("your.package.name") .matchAllClasses(new ClassMatchProcessor() < @Override public void processMatch(Class klass) < classes.add(klass); >>).scan(); return classes; > 

How to find all classes in a package using reflection in kotlin, The Reflections library is pretty straight forward and has a lot of additional functionality like getting all subtypes of a class, get all

Find all classes in package (& call static methods) at runtime

Upon encountering this question, I found it to be engaging and decided to devise a solution. The challenge lies in identifying all the classes belonging to a particular package.

Assuming all classes reside in the same package as C , and all classes except for C contain an inaccessible onLoad method, the following code example can be utilized.

public final class C < public static void main(String[] args) throws Exception < for (Class cls : getClasses(C.class)) < if (cls != C.class) < Method onLoad = cls.getDeclaredMethod("onLoad"); onLoad.setAccessible(true); onLoad.invoke(null); >> > private static List> getClasses(Class caller) throws IOException, URISyntaxException < return Files.walk(getPackagePath(caller)) .filter(Files::isRegularFile) .filter(file ->file.toString().endsWith(".class")) .map(path -> mapPathToClass(path, caller.getPackage().getName())) .collect(Collectors.toList()); > private static Class mapPathToClass(Path clsPath, String packageName) < String className = clsPath.toFile().getName(); className = className.substring(0, className.length() - 6); return loadClass(packageName + "." + className); >private static Path getPackagePath(Class caller) throws IOException, URISyntaxException < String packageName = createPackageName(caller); Enumerationresources = caller.getClassLoader() .getResources(packageName); return Paths.get(resources.nextElement().toURI()); > private static String createPackageName(Class caller) < return caller.getPackage().getName().replace(".", "/"); >private static Class loadClass(String name) < try < return Class.forName(name); >catch (ClassNotFoundException e) < return null; >> > 

To streamline the code, I've excluded exception checking and any statements that may result in an exception, including resources.nextElement() . Therefore, if you wish to handle such scenarios, some additional checks will need to be inserted.

Читайте также:  Css волнистая линия подчеркивания

The reflections library is at your disposal.

. import org.reflections.Reflections; import org.reflections.scanners.ResourcesScanner; import org.reflections.scanners.SubTypesScanner; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; import org.reflections.util.FilterBuilder; public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException < Reflections reflections = new Reflections(new ConfigurationBuilder() .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner()) .setUrls(ClasspathHelper.forClassLoader(ClasspathHelper.contextClassLoader())) .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("com.foo.bar.asd")))); Set> classes = reflections.getSubTypesOf(Object.class); for (Class clazz : classes) < Method method = clazz.getMethod("onLoad"); method.invoke(null); >>

Kindly take into account that guava.jar and javassist.jar are also required as dependencies for this library.

Check, if all classes in project have a specific annotation, The Java Reflection API can be used to check the annotations of a class. E.g. the following code prints the name and value of each class

Источник

Java - Find Files in classpath under a Folder And SubFolder

This tutorial shows how to get the list of resources (files) from a classpath directory and subdirectory.

Examples

Example resource directory structure

D:\files-in-classpath-under-folder-and-subfolder>tree /a /f src/main/resources
Folder PATH listing
Volume serial number is B2F7-682A
D:\FILES-IN-CLASSPATH-UNDER-FOLDER-AND-SUBFOLDER\SRC\MAIN\RESOURCES
| a.txt
|
+---subfolder1
| b.txt
|
\---subfolder2
| c.txt
|
\---subsubfolder21
d.txt

Using plain Java

package com.logicbig.example; import java.io.File; import java.io.IOException; import java.net.URL; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; public class FilesInClassPathJavaExample < public static void main(String[] args) < System.out.println("-- under subfolder2 --"); ListresourceFolderFiles = getResourceFolderFiles("subfolder2"); resourceFolderFiles.stream().filter(f -> f.getName().endsWith(".txt")).forEach(System.out::println); System.out.println("-- under all folders in classpath --"); resourceFolderFiles = FilesInClassPathJavaExample.getResourceFolderFiles(""); resourceFolderFiles.stream().filter(f -> f.getName().endsWith(".txt")).forEach(System.out::println); > static List getResourceFolderFiles(String folder) < ClassLoader loader = Thread.currentThread().getContextClassLoader(); URL url = loader.getResource(folder); String path = url.getPath(); File file = new File(path); Listfiles = new ArrayList<>(); if(file.isDirectory()) < try < Files.walk(file.toPath()).filter(Files::isRegularFile).forEach(f ->files.add(f.toFile())); > catch (IOException e) < throw new RuntimeException(e); >>else < files.add(file); >return files; > >
-- under subfolder2 -- D:\files-in-classpath-under-folder-and-subfolder\target\classes\subfolder2\c.txt D:\files-in-classpath-under-folder-and-subfolder\target\classes\subfolder2\subsubfolder21\d.txt -- under all folders in classpath -- D:\files-in-classpath-under-folder-and-subfolder\target\classes\a.txt D:\files-in-classpath-under-folder-and-subfolder\target\classes\subfolder1\b.txt D:\files-in-classpath-under-folder-and-subfolder\target\classes\subfolder2\c.txt D:\files-in-classpath-under-folder-and-subfolder\target\classes\subfolder2\subsubfolder21\d.txt

Using Spring PathMatchingResourcePatternResolver

package com.logicbig.example; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import java.io.File; import java.io.IOException; public class FilesInClassPathSpringExample < public static void main(String[] args) throws IOException < System.out.println("-- under subfolder2 --"); PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); Resource[] resources = resourcePatternResolver.getResources("classpath:subfolder2/**/*.txt"); for (Resource resource : resources) < File file = resource.getFile(); System.out.println(file); >System.out.println("-- under all folders in classpath --"); PathMatchingResourcePatternResolver resourcePatternResolver2 = new PathMatchingResourcePatternResolver(); Resource[] resources2 = resourcePatternResolver.getResources("classpath:**/*.txt"); for (Resource resource : resources2) < File file = resource.getFile(); System.out.println(file); >> >
-- under subfolder2 -- D:\files-in-classpath-under-folder-and-subfolder\target\classes\subfolder2\c.txt D:\files-in-classpath-under-folder-and-subfolder\target\classes\subfolder2\subsubfolder21\d.txt -- under all folders in classpath -- D:\files-in-classpath-under-folder-and-subfolder\target\classes\a.txt D:\files-in-classpath-under-folder-and-subfolder\target\classes\subfolder1\b.txt D:\files-in-classpath-under-folder-and-subfolder\target\classes\subfolder2\c.txt D:\files-in-classpath-under-folder-and-subfolder\target\classes\subfolder2\subsubfolder21\d.txt

Example Project

Dependencies and Technologies Used:

Источник

Оцените статью