How Do I Search a File Created Using Java Servlet?
Java servlet applications allow you to create software that runs on any operating system. Java programming is not compiled until it is executed on the machine, which makes it compatible with a wide range of operating systems. One function you can perform using Java code is the search of files on a user's machine. This is beneficial when you want to create an application that finds files relative to search criteria set by the user or your own software.
Instructions
-
-
1
Add the file input and output libraries. These Java libraries provide you with all of the internal functions for file searches, creating and editing files on a server or desktop. Add the code below to the beginning of your code file:
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.util.Collection;
import java.util.Iterator;
-
2
Set the directory where the search executes. You can set it to search the entire "C" drive or just a subdirectory. The code below sets the directory for the search:
File root = new File("C:\documents\");
-
-
3
Set the file extensions to search. Use "*" to search for all file extensions. In this example, all of the "txt" files are searched. The code below sets the "txt" extension:
String[] extensions = {"txt"};
-
4
Set your file collection object. The file collection object uses all of the parameters and sets up the search. The code below displays how to set up the collection object:
Collection files = FileUtils.listFiles(root, extensions, true);
-
5
Run the search on the computer. In this example, each file found with the "txt" extension is displayed to the user. The code below performs the search and display:
for (Iterator iterator = files.iterator(); iterator.hasNext();) {
File pfile = (File) iterator.next();
System.out.println("File Found: " + pfile.getAbsolutePath());
}
-
1
References
- Photo Credit java hot and black image by Pix by Marti from Fotolia.com