I need go through a package with sub-packages that contains some java class file. Can someone teach me how to get all those java class file directories and store it in a String array?
public void getClassArray(File dir, List<String> results) {
File[] filesInDir = dir.listFiles();
for (File file : filesInDir) {
if (file.isDirectory()) {
getClassArray(file, results);
}
else if (file.getName().endsWith(".class")) {
results.add(file.getName());
}
}
}
can this work?
The other post will give you all the class file name the below code snippet will give you all the folders which have .class files within
public void getClassFolders(File file, List<String> fileNames){
for (File child : file.listFiles()) {
if(child.isDirectory()){
getClassFolders(child, fileNames);
} else if(child.getName().endsWith(".class")){
fileNames.add(file.getName());
}
}
}
Related
I did this simple experiment to list all files/directory in a parent directory.
Did this by making a java project in eclipse by name 'JavaProject' and a class 'Temp.java' under src/com. Code is as below:
public class Temp {
public static void main(String[] args) {
search("../JavaProject");
}
public static void search(String dName) {
String[] files = new String[100];
File search = new File(dName); // make file object
if (!search.isDirectory()) {
return;
}
files = search.list(); // create the list
for (String fn : files) {// iterate through it
System.out.print(" " + fn);
File temp = new File(fn);
if (temp.isDirectory()) {
search(fn);
}
System.out.println();
}
}
}
The file structure is as below :
JavaProject(dir)
.classpath(file)
.project(file)
.settings(dir)
org.eclipse.jdt.core.prefs(file)
bin(dir)
com(file)
Temp.class(file)
src(dir)
com(dir)
Temp.java(file)
When I run the above program, it gives the following output:
.classpath
.project
.settings org.eclipse.jdt.core.prefs
bin com
src com
I cant understand why it does not print the .java file and .class file inside the com folders.
When I try debugging then the file object on 'com' returns 'false' for both isDirectory() and isFile() methods.
When it gets to the 'com' directory your code is doing:
File temp = new File("com");
Since you have not specified any path this will be taken to be relative to the current directory which is not the directory containing 'com'.
You should use something like:
File temp = new File(parent, fn);
where parent is the File object for the parent directory.
You can use listFiles() instead of list(). See below example:
public class Program {
public static void main(String args[]) throws IOException {
search(new File("."), 0);
}
public static void search(File file, int level) {
if (!file.isDirectory()) {
return;
}
for (File f : file.listFiles()) {
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println(f.getName());
if (f.isDirectory()) {
search(f, ++level);
}
}
}
}
I asked a question about how to delete all files from folders in a directory but keep the folders, this can be found here:
How to delete files of a directory but not the folders
One of the purposed solutions was to use recursion, to achieve this:
public void DeleteFiles() {
File file =
new File(
"D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/"+
"resources/pdf/");
System.out.println("Called deleteFiles");
if (file.isDirectory()) {
for (File f : file.listFiles()) {
DeleteFiles();
}
} else {
file.delete();
}
}
However I just get a console full of Called deleteFiles, until I get the stack overflow error, it does not seem to go through the directory to find files and delete them, how can I achieve this?
Recursion is asking for trouble when there are much simpler solutions. With commons-io:
import java.io.File;
import org.apache.commons.io.FileUtils;
import static org.apache.commons.io.filefilter.TrueFileFilter.TRUE;
File root = new File("D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/pdf/");
Iterator<File> files = FileUtils.iterateFiles(root, TRUE, TRUE);
for (File file : files) {
file.delete();
}
or with JDK 7:
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
Path root = Paths.get("D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/pdf/");
Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
file.delete();
return FileVisitResult.CONTINUE;
}
})
public void DeleteFiles() {
File file = new File("D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/pdf/");
System.out.println("Called deleteFiles");
DeleteFiles(file);
}
public void DeleteFiles(File file) {
if (file.isDirectory()) {
for (File f : file.listFiles()) {
DeleteFiles(f);
}
} else {
file.delete();
}
}
File file = new File("D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/pdf/");
You are creating the same file again and again. Declare that file outside the function.
Your recursion is different from the suggested one.
public void DeleteFiles( File file) {
System.out.println("Called deleteFiles");
if (file.isDirectory()) {
for (File f : file.listFiles()) {
DeleteFiles(f);
}
} else {
file.delete();
}
}
When I run a class with the following code:
public static void main(String[] args)
{
createDuplicateStructure("in", "out");
}
public static void createDuplicateStructure(String path_start, String path_result)
{
File start = new File(path_start);
File result = new File(path_result);
duplicateDirectoryStructure(start, result);
}
public static void duplicateDirectoryStructure(File start_dir, File result_dir)
{
//FileFilter used by listFiles(filter) - to make sure they are dirs
FileFilter dirs_only = new FileFilter()
{
public boolean accept(File file){ return file.isDirectory();}
};
File[] dir_contents = start_dir.listFiles(dirs_only);
for(File dir : dir_contents)
{
File duplicate = new File(result_dir.getPath(), dir.getName());
if(dir.mkdir())
{
duplicateDirectoryStructure(dir, duplicate);
}
else
{
System.out.println("ERROR: Unable to create dir! (" + duplicate.getPath() + ")");
}
}
}
I get this in the console:
Error: Unable to create dir! (out/a)
Error: Unable to create dir! (out/a)
Error: Unable to create dir! (out/a)
The directory "out" is in the same directory as the .jar.
There is a directory "in" which contains "a", "b", and "c" directories (for testing).
Any ideas why this is not working?
Thanks!
You should replace dir.mkdir() with duplicate.mkdir() because dir is the already existing source directory.
dir.mkdir() only returns true the directory was actually created. Try doing
if(dir.mkdir() || dir.exists())
The line
`if(dir.mkdir())`
is trying to create the existing directory structure
if you change it to
if(duplicate.mkdir())
you get another problem where it tries to create the a subdirectory under out which does not exist yet.
So change it to
if(duplicate.mkdirs())
which will create the directory structure, or create the out directory before you start your loop.
enter code hereI wrote the following code which searches a folder directory recursively to find a specific folder.
The program is supposed to do check the folder name and if the folder name is "src", then it should go into that folder to get all the files. Currently the program is getting all the files from all the directories.
public class Main {
public static void main(String[] args) {
File fileObject = new File("C:\\Users\\lizzie\\Documents\\");
recursiveTraversal(fileObject);
}
public static void recursiveTraversal(File fileObject)
{
if (fileObject.isDirectory())
{
File allFiles[] = fileObject.listFiles();
for(File aFile : allFiles){
recursiveTraversal(aFile);
}
}
else if (fileObject.isFile())
{
System.out.println(fileObject.getAbsolutePath());
}
}
}
when I check if a certain folder is a directory, I added the following constraint but that didn't help.
if (fileObject.isDirectory() && fileObject.getName().equals("src"))`
Please let me know what I can do to improve my code. Anything will be appreciated.
Thanks
If you look at your if-else inside recursiveTraversal, you'll see that you're printing anything that isn't a directory, regardless of where it is. Here's a fix:
public class Main {
public static void main(String[] args) {
File fileObject = new File("C:\\Users\\lizzie\\Documents\\");
recursiveSearch(fileObject);
}
public static void recursiveSearch(File fileObject) {
if (fileObject.isDirectory()) {
if (fileObject.getName().equals("src")) {
recursivePrint(fileObject);
} else {
File allFiles[] = fileObject.listFiles();
for(File aFile : allFiles){
recursiveSearch(aFile);
}
}
}
// ignore non-directory objects during search
}
public static void recursivePrint(File fileObject)
{
if (fileObject.isDirectory())
{
File allFiles[] = fileObject.listFiles();
for(File aFile : allFiles){
recursivePrint(aFile);
}
}
else if (fileObject.isFile())
{
System.out.println(fileObject.getAbsolutePath());
}
}
}
This will print all the files recursively of any directory named src.
What you need to do is put the constraint on what's being printed, not what's being traversed. As you've noticed, the traversal is working fine, since it gets all files in all subfolders.
If you want to print only the filenames inside of the "src" directory (not in subdirectories), then you can do...
...
else if (fileObject.isFile() && fileObject.getParent().getName().equals("src")
{
System.out.println(fileObject.getAbsolutePath());
}
...
If you want to print what's in the "src" directory, and all subdirectories, then you'll need to break your algorithm into two parts
find the "src" folder, then
use your current algorithm to print everything in all directories from there and lower
Instead of checking for .equals() on the name, check if the name contains "src" using either fileObject.getName().contains(StringBuffer) or fileObject.getName().indexOf("src") != -1
Here is the code I have thus far:
import java.io.*;
class JAVAFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.endsWith(".java"));
}
}
public class tester {
public static void main(String args[])
{
FilenameFilter filter = new JAVAFilter();
File directory = new File("C:\\1.3\\");
String filename[] = directory.list(filter);
}
}
At this point, it'll store a list of all the *.java files from the directory C:\1.3\ in the string array filename. However, i'd like to store a list of all the java files also in subdirectories (preferably with their path within C:\1.3\ specified also. How do I go about doing this? Thanks!
you should look at DirectoryWalker from Apache
I'm afraid you can't do it with the list(FilenameFilter) method. You'll have to list all files and directories, and then do the filtering yourself. Something like this:
public List<File> getFiles(File dir, FilenameFilter filter) {
List<File> ret = new ArrayList<File>();
for (File f : dir.listFiles()) {
if (f.isDirectory()) {
ret.addAll(getFiles(f, filter));
} else if (filter.accept(dir, f.getName())) {
ret.add(f);
}
}
return ret;
}
As far as I know, you will have to do this manually (recursively), i.e. you will have to call list(filter) for all sub-directories of C:\1.3\, and so on....