As a system engineer of SIer, I spend every day earning daily money, but recently I had the opportunity to create a design document (?) That says, "List the created Java classes by giving them package names." It's a reckless story that manual work is troublesome because of the number of Java classes created. Therefore, I decided to write a program that recursively searches for __packages and outputs a list of classes with package names. Below is a sample.
For example, if you have a project with the above package structure, the program that outputs the classes under "jp.co" with the package name should be as follows.
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Enumeration;
import java.util.PriorityQueue;
public class Main {
private static final String PACKAGE_SEPARATOR = ".";
private static final String CLASS_SUFFIX = ".class";
public static void main(String[] args) throws IOException, URISyntaxException {
//Use the class loader to get the resources under the package.
String rootPackageName = "jp.co".replace(PACKAGE_SEPARATOR, File.separator);
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
Enumeration<URL> rootUrls = classLoader.getResources(rootPackageName);
//Recursively search directories".class"If you find a file that ends with
//After formatting the character string, store it in the list.
PriorityQueue<String> classNames = new PriorityQueue();
while (rootUrls.hasMoreElements()) {
URL rootUrl = rootUrls.nextElement();
Path rootPath = Paths.get(rootUrl.toURI());
Files.walkFileTree(rootPath, new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
String pathName = path.toString();
if (pathName.endsWith(CLASS_SUFFIX)) {
int beginIndex = pathName.lastIndexOf(rootPackageName);
int endIndex = pathName.lastIndexOf(CLASS_SUFFIX);
String className = pathName.substring(beginIndex, endIndex)
.replace(File.separator, PACKAGE_SEPARATOR);
classNames.add(className);
}
return super.visitFile(path, attrs);
}
});
}
//Output a list of found class names.
for (String className : classNames) {
System.out.println(className);
}
/*
jp.co.first.ClassA
jp.co.first.ClassB
jp.co.first.sub.ClassC
jp.co.first.sub.ClassD
jp.co.second.ClassE
jp.co.second.ClassF
*/
}
}
Recommended Posts