HOW TO: read all files in a directory

In unix-based systems, a directory is really just a different type of file. If you create a File object out of a “path/to/some/files” there is an easy way to get a listing of all the files in an array.

WARNING: there are such things as “hidden files.” Hidden files begin with a ‘dot’ (.). For example, you’ll notice a lot of macs insert a file called “.DS_Store” into directories - which is uses to keep track of graphical information about how you browsed the directory.

Here is some commented code that shows the process:

String dirPath = “/path/to/files/”;

//1. Create a new File object out of the path.
File someDir = new File(dirPath);
//2. If the File is a directory, .list() will return
// an array of Strings each of which is some file that
// exists in the directory.
String[] files = someDir.list();

//3. process the files in the directory.
// Each string in the array is some file in the directory.
// If you want to read the file YOU MUST pre-pend the directory
// path to the file name in order for the program to find it.
// (Otherwise, it would just assume the file is in the same
// directory as the program.)
// Below, I do a full scanning of each document and just print each
// word found on a line.
Scanner S;
for(int i=0; i<files.length; i++){
  S = new Scanner(dirPath+files[i]);

  while(S.hasNext()){
    System.out.println(S.next());
  }
}

Leave a Reply