Hi. I'd like to do a search for folders/directories from java, and go into those folders/directories in java. I guess it's called system utilities? Any tutorials out there, or books on the subject?
Thanks ;)
Hi. I'd like to do a search for folders/directories from java, and go into those folders/directories in java. I guess it's called system utilities? Any tutorials out there, or books on the subject?
Thanks ;)
I use this code to get all ZIP files in a folder. Call this recursively checking for the file object to be a sub directory again and again.
public List<String> getFiles(String folder) {
List<String> list = new ArrayList<String>();
File dir = new File(folder);
if(dir.isDirectory()) {
FileFilter filter = new FileFilter() {
public boolean accept(File file) {
boolean flag = false;
if(file.isFile() && !file.isDirectory()) {
String filename = file.getName();
if(!filename.endsWith(".zip")) {
return true;
}
return false;
}
};
File[] fileNames = dir.listFiles(filter);
for (File file : fileNames) {
list.add(file.getName());
}
return list;
}
If you want to navigate the file system, take a look at File and the list() method. You'll most likely require some recursive method to navigate down through the hierarchies.
I don't know of any tutorials or books on that particular subject, but the way to do it is to use the java.io.File
class. For example, you can use the list()
to get a list of the contents of a directory. Then it's just a matter of using isDirectory()
and recursing to search an entire file tree.
You could use Apache Commons FileUtils (see: http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html) and specifically the listFiles method there, which can do this recursively and use filters (so it saves you the writing of the recursion yourself and answers the search you mentioned).
here is another example:
for (File file : File.listRoots()[0].listFiles()) {
System.out.println(file);
}
the same, printing only directories:
FileFilter isDirectory = new FileFilter() {
public boolean accept(File pathname) {
return pathname.isDirectory();
}
};
for (File file : File.listRoots()[0].listFiles(isDirectory)) {
System.out.println(file);
}
Good example: http://www.leepoint.net/notes-java/io/10file/20recursivelist.html
BTW. I recommend reading the whole thing. http://www.leepoint.net/notes-java/
I used Apache Commons VFS.
Is nice to use it for read contents of a directory, like this:
FileSystemManager fsManager = VFS.getManager();
FileObject path = fsManager.resolveFile( "file:///tmp" );
FileObject[] children = path.getChildren();
System.out.println( "Children of " + path.getName().getURI() );
for ( int i = 0; i < children.length; i++ )
{
System.out.println( children[ i ].getName().getBaseName() );
}
You can check if children is file, folder or something different with getType().
And same code works for reading ZIP or JAR files, FTP, SFTP, ... just changing the URL of resolveFile as you can see here.