Follow along with the video below to see how to install our site as a web app on your home screen.
Note: This feature may not be available in some browsers.
import java.util.*;
import java.io.*;
/**
* @author javapractices.com
* @author Alex Wong
*/
public final class FileListing {
/**
* Demonstrate use.
*/
public static void main(String[] aArguments) throws FileNotFoundException {
// Syötteenä tuleva kansio josta halutaan etsiä (ja syvempää)
File tempDir = new File(aArguments[0]);
// Kutsuu metodia getFileListing joka palauttaa listauksen
List files = FileListing.getFileListing( tempDir );
//print out all file names, and display the order of File.compareTo
Iterator filesIter = files.iterator();
while( filesIter.hasNext() ){
System.out.println( filesIter.next() );
}
}
/**
* Recursively walk a directory tree and return a List of all
* Files found; the List is sorted using File.compareTo.
*
* @param aStartingDir is a valid directory, which can be read.
*
* Otherwise ok, but needs a filter to leave only the fonts
*/
static public List getFileListing( File aStartingDir ) throws FileNotFoundException{
validateDirectory(aStartingDir);
List result = new ArrayList();
File[] filesAndDirs = aStartingDir.listFiles(new PhilePhilter());
List filesDirs = Arrays.asList(filesAndDirs);
Iterator filesIter = filesDirs.iterator();
File file = null;
while ( filesIter.hasNext() && ) {
file = (File)filesIter.next();
result.add(file); //always add, even if directory
if (!file.isFile()) {
//must be a directory
//recursive call!
List deeperList = getFileListing(file);
result.addAll(deeperList);
}
}
Collections.sort(result);
return result;
}
/*
* Class to filter out files that don't have
* the correct extension.
*/
static class PhilePhilter implements FilenameFilter
{
public boolean accept(File dir, String file)
{
return (file.toUpperCase().indexOf(".GIF") != -1);
}
}
/**
* Directory is valid if it exists, does not represent a file, and can be read.
*/
static private void validateDirectory (File aDirectory) throws FileNotFoundException {
if (aDirectory == null) {
throw new IllegalArgumentException("Directory should not be null.");
}
if (!aDirectory.exists()) {
throw new FileNotFoundException("Directory does not exist: " + aDirectory);
}
if (!aDirectory.isDirectory()) {
throw new IllegalArgumentException("Is not a directory: " + aDirectory);
}
if (!aDirectory.canRead()) {
throw new IllegalArgumentException("Directory cannot be read: " + aDirectory);
}
}
}
Indeed, I did notice your code is made out of many diferent sources all mixed into one. That is cannibalism worthy of the greatest programmerdropadrop said:Thanks for the help. I managed to find a few examples of how to use listFiles, and got it to work in a way that it lists everything in folders and subfolders. I'm now trying to get it to filter out so it only shows files with a certain extension and it's not working. The following is combined from some of the examples I found:
Well, i got good news and bad news. The good news is that yes, the PhilePhilter works great. The bad news is that the rest doesn'tdropadrop said:I believe the PhilePhilter should work as it's almost a direct rip from the original example. The problem is probably with the way it's implemented... Is it returning a value that I should allwasy check somewhere?
Sure, that works well to. I't not how I would design it, but I just tested it and it works fine. In order for it to work just remake your PhilePhilter to return true either if your file is a directory, or if the file is a .gif file.dropadrop said:So basicly you are saying I should let it create a list with all the files and folders, and then I should filter down that list to find the ones I need?
import java.util.*;
import java.io.*;
/**
* @author javapractices.com
* @author Alex Wong
*/
public final class FileListing {
/**
* Demonstrate use.
*/
public static void main(String[] aArguments) throws FileNotFoundException {
// Receives the root folder where the search is started from
File tempDir = new File(aArguments[0]);
// get a fileListing from local disk
List files = FileListing.getFileListing( tempDir );
// narrows down the previous list to only include files with .GIF extensions
List sortedFiles = FileListing.getGifListing( files, ".GIF" );
//print out all file names, and display the order of File.compareTo
Iterator filesIter = sortedFiles.iterator();
while( filesIter.hasNext() ){
System.out.println( filesIter.next() );
}
}
/**
* Recursively walk a directory tree and return a List of all
* Files found; the List is sorted using File.compareTo.
*
* @param aStartingDir is a valid directory, which can be read.
*
* Otherwise ok, but needs a filter to leave only the fonts
*/
static public List getFileListing( File aStartingDir ) throws FileNotFoundException{
validateDirectory(aStartingDir);
List result = new ArrayList();
File[] filesAndDirs = aStartingDir.listFiles();
List filesDirs = Arrays.asList(filesAndDirs);
Iterator filesIter = filesDirs.iterator();
File file = null;
while ( filesIter.hasNext() ) {
file = (File)filesIter.next();
result.add(file); //always add, even if directory
if (!file.isFile()) {
//must be a directory
//recursive call!
List deeperList = getFileListing(file);
result.addAll(deeperList);
}
}
Collections.sort(result);
return result;
}
// Search a list for specified files and return a new list only including them.
static public List getGifListing( List aStartingPoint, String name ) {
List allFiles = aStartingPoint;
List sortedFiles = new ArrayList();
Iterator filesIter = allFiles.iterator();
File file = null;
while( filesIter.hasNext()) {
file = (File)filesIter.next();
if (file.getName().toUpperCase().indexOf(name) != -1);
sortedFiles.add(file);
}
return sortedFiles;
}
/*
* Class to filter out files that don't have
* the correct extension.
*
* Thanks go to Google and Marco
*/
static class PhilePhilter implements FilenameFilter
{
public boolean accept(File dir, String file)
{
return (file.toUpperCase().indexOf(".GIF") != -1);
}
}
/**
* Directory is valid if it exists, does not represent a file, and can be read.
*/
static private void validateDirectory (File aDirectory) throws FileNotFoundException {
if (aDirectory == null) {
throw new IllegalArgumentException("Directory should not be null.");
}
if (!aDirectory.exists()) {
throw new FileNotFoundException("Directory does not exist: " + aDirectory);
}
if (!aDirectory.isDirectory()) {
throw new IllegalArgumentException("Is not a directory: " + aDirectory);
}
if (!aDirectory.canRead()) {
throw new IllegalArgumentException("Directory cannot be read: " + aDirectory);
}
}
}
if (file.getName().toUpperCase().indexOf(name) != -1);
sortedFiles.add(file);
Nemezer said:I'm afraid that I must hand you a baseball bat so that you may hit yourself on the head with it.
C:\Documents and Settings\Mika\Omat tiedostot\my_java\fonts\Fonts\classes>java F
ileListing c:\
Exception in thread "main" java.lang.NullPointerException
at java.util.Arrays$ArrayList.<init>(Unknown Source)
at java.util.Arrays.asList(Unknown Source)
at FileListing.getFileListing(FileListing.java:45)
at FileListing.getFileListing(FileListing.java:55)
at FileListing.main(FileListing.java:20)
static public List getFileListing( File aStartingDir ) throws FileNotFoundException{
validateDirectory(aStartingDir);
List result = new ArrayList();
File[] filesAndDirs = aStartingDir.listFiles();
// Test if it gets this far
System.out.println("success 1");
List filesDirs = Arrays.asList(filesAndDirs);
Iterator filesIter = filesDirs.iterator();
File file = null;
while ( filesIter.hasNext() ) {
file = (File)filesIter.next();
result.add(file); //always add, even if directory
if (!file.isFile()) {
//must be a directory
//recursive call!
List deeperList = getFileListing(file);
result.addAll(deeperList);
}
}
Collections.sort(result);
return result;
}
File[] filesAndDirs = aStartingDir.listFiles();
// New code
if (filesAndDirs == null)
return result;
// End new code
List filesDirs = Arrays.asList(filesAndDirs);
American beerdropadrop said:You are a lifesaviour!
If I ever come to the states I'll buy you a beer.
Nemezer said:American beer
In anycase you'd have a hard time finding me in the states since I'm a Canadian. But if your offer also applies to the Canadian beer, count me in
As always, spread some Java LOVE Power
Just thought I'd point out that Java does have a contains(String) method, which is much more succinct. Perhaps more relevantly, there is an endsWith(String) method that's probably even more useful (or accurate, at least) for the purposes of a filename extension filter.Nemezer said:Code:if (file.getName().toUpperCase().indexOf(name) != -1); sortedFiles.add(file);