File SorterIn this article, I will show you how to write a Java application that will read a directory on your local computer and sort the files depending on their file type. Before we begin, we need to prepare a folder for our project with all of our test files in it. I have created a folder in “C:\Workspaces\Eclipse\Examples” called “example_files”. This folder contains six files comprised of two files for each of three files types. I have “.jpg”, “.bmp”, and “.txt” file types, but you can extend this application to handle other file types as needed.

To begin the file sorter, we need to create a class with a main constructor just as we did in the HelloWorld project. I will call mine “FileSorter”, but you can name yours whatever you’d like. After you’ve created your class, begin it by adding an import for the “java.io.File” package. After that, we need to define our folder path by using the File object. We can do that with the following code:

File folder = new File(“C:\\Workspaces\\Eclipse\\Examples\\example_files“);

The File object is simply an abstract representation of file and directory pathnames. It can be used to gather information about files and folders such as absolute path, canonical path, parent, free space, etc… and allows you to delete, rename, make directories, etc… Checkout the Java File API docs at http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html for more information.

Moving on. Now that we have defined the folder that contains our test files, we need to read those files into a list using a File array.

File[] files = folder.listFiles();

Pretty simple, huh? After we have our files listed in an array, we are free to do whatever we want with them. For this example, we will use a for loop to iterate through the list of files and will move them into folders depending on their file types. Inside that loop, we will first check to see if the file we’re reading is indeed a file. If it is, we’ll process it. If it is another directory, we’ll simply ignore it and move onto the next file in the list. While all of this is going on, we will also check to see if we have a folder to store the files into. The folders will be named based on the extensions used in each of our files.

So, let’s begin by setting up our for loop.

for(int i = 0; i < files.length; i++){
}

Inside our for loop, we need to first check if the file we’re working with is a directory and skip it if it is.

if(!files[i].isDirectory()){
}

If the file we’re working with in the loop is not a directory, we need get some information about it. The first thing we need to get is the file name. Though this isn’t extremely important, it does make it a little easier to reference the file name than by typing the fully qualified code when referencing it. The next thing we need get from the file is its extension. Unfortunately, the File object we’re working with does not provide an easy method for getting the extension. Instead, we will determine the file extension by use of the lastIndexOf  function that the String object provides us. (This is where defining the file name comes in handy.) Anyways, we use lastIndexOf  to find out where the last location of the “.” (period) is located in the file name. If we don’t find a period in the file name, we will assume the file doesn’t have an extension. However, if we do find a period in the file name, we will use a substring to assume anything after the last period is the extension.

String filename = files[i].getName();
String ext = (filename.lastIndexOf(“.”) == -1) ? “” : filename.substring(filename.lastIndexOf(“.”) + 1, filename.length());

The next thing we need to do is to create a reference to the folders we will be moving our files into. We will do this by checking if a folder is created with the name of the extension of the current file in the loop. If we do not already have a folder with the same name as the extension for the current file, we will create a new folder.

File storageFolder = new File(folder.getPath() + “/” + ext);
if(!storageFolder.exists()){
storageFolder.mkdir();
}

Once we have a folder created for our file, all we have left to do is to move it into the folder. To do that, we will use the renameTo  function provided by the File object. This function returns a boolean telling us whether the file was moved successfully or not. For now, we’re not going to worry about whether it moved successfully or not. But, in a real world scenario you would probably need to add some sort of logic telling your application what to do if it fails. You could tell it to try again, print an error, or move the file into another folder. For now, we’ll just assume the file gets moved successfully.

boolean success = files[i].renameTo(new File(storageFolder, filename));

We are now ready to execute the code. After running the application, open an Explorer window and navigate to the folder that originally contained your files. You should now see sub-folders instead of the files and the files should be inside those folders.

Filter Sorter - Before and After

I know that you can do the same thing this application does by sorting an Explorer window by file type and by manually moving the files into their corresponding folders. But, where’s the fun in that? Besides, you can easily extend this to do other things like moving images into different folders depending on their width & height or by grouping files into folders depending on their file sizes or their created and modified dates. The possibilities are endless. So, you decide how you want to use this.

Here is the complete code with comments.

import java.io.File;

public class FileSorter {
	public static void main(String[] args) {
		// Folder that contains our images
		File folder = new File("C:\Workspaces\Eclipse\Examples\example_files");
		
		// Read the files from our folder into an array
		File[] files = folder.listFiles();
		
		// Iterate list of files
		for(int i = 0; i < files.length; i++){
			// Check if the current file is a directory
			// Skip it if it is and process is if it's not
			if(!files[i].isDirectory()){
				
			  // Get the filename
			  String filename = files[i].getName();
			  
			  // Get the file extension
			  String ext = (filename.lastIndexOf(".") == -1) ? "" : filename.substring(filename.lastIndexOf(".") + 1, filename.length());
			
			  // Print the filename and extension for reference and
			  // for testing our code
			  System.out.println("File: " + filename + " - Extension: " + ext);
			  
			  // Define a reference to the folder that will store our files
			  // depending on its file type
			  File storageFolder = new File(folder.getPath() + "/" + ext);
			  
			  // If the folder does not exist, create it. Otherwise, ignore it
			  if(!storageFolder.exists()){
				  storageFolder.mkdir();
			  }
			  
			  // Move the file into the folder that has a name the same as
			  // the extension of the file
			  boolean success = files[i].renameTo(new File(storageFolder, filename));
			}
		}
	}
}

If you enjoyed this post, please consider making a donation.

Related Posts

Tagged with:  

Leave a Reply