This post gives you the material to select or filter files in a directory. It is not a ‘real’ tutorial, but rather gives you means to play with the code with immediate results. By playing you get quicker understanding how things work. At least I do. The code filters xml-files, but by changing one line of code you can filter any extension you wish. After you ran the java program you end up having a text file containing the list of files which met your criteria. I do suppose you already have finished the HelloWorld.java part with succes. Otherwise finish this first. YouTube is full of HelloWorlds. You can use this project or create a new fresh one if you prefer.
I am using Netbeans on a Mac. Windows users have to use their own directory annotation. For example c:\user\myNetbeansProjects\HelloWorld\ instead of ./user/etc.
Before using the code you have to create a file folder in the HelloWorld project directory. After creating the logs directory your project looks like this in your Windows Explorer or Finder.
Second we need to fill our logs-directory with dummy files. You can make your own dummies or download and unzip DummyXMLs into your new logs directory, also by using the Explorer. Variety in file extensions is key, because we want to demonstrate we actually picked the files we wanted to. When you’re done creating the dummy files the log-directory should contain (1) one or more .xml-files, (2) files with an extension other than .xml and (3) a filename like logfile.xml.txt which should be excluded by our code. For now content does not matter. You can leave the file content empty if you want to. The code only looks at the extension of the files. It doesn’t look at the content.
After these steps your log-directory in your Hello World project should resemble this:
Now we open up your Hello World-project in Netbeans and you will see Netbeans picked up the log directory and dummy files you just created.
Download and run the code
Next step is downloading FilterLogFiles.java and unzip it in the same src-directory you saved your HelloWorld.java.
The explanation of the code is in the file itself. I have put many comments to make clear what happens where. Once you’ve unzipped, you can switch back to your project in Netbeans. FilterLogFiles.java shows up in the same directory where your HelloWorld.java is saved. To be sure everything will work from the beginning make a clean build of the HelloWorld project in NetBeans.
The last thing you have to do is opening FilterLogFiles.java and hit the Netbeans Run button. Or use shift-F6. After it ran successfully you see the files the program has selected in your console.
In your project root directory is also a new text file “FilteredLogFileList.txt” created. In case you check it inside you’ll see the names of the selected files. Running the program again will overwrite the former version.