In this article we will look into how we can use a File Object to read directories and some subtle details.
A directory File Object is created by passing the directory path to the constructor.
We can convert a directory to a URL, this is helpful while creating a classloader.
To get all the files in a directory.
A directory File Object is created by passing the directory path to the constructor.
File dir = new File("/test/file/demo");
But having a File Object does not mean that it corresponds to a real file on the disk so we need to make sure the file exits and the directory is valid.File APIs
In fact, its a good practice to check all the three below and make sure they hold true.- File exists
- File is a directory
- Directory can be read
dir.exists()
When user is relying on third party open sources, most of the times they need configure it and at times it involves setting directory paths. For example in case of a test framework, we may have to set the directory where the test results will be written. As a framework author, one must make sure the path entered by the user is correct.dir.isDirectory()
dir.canRead()
We can convert a directory to a URL, this is helpful while creating a classloader.
URL dirUrl = dir.toURI().toURL();
Read files from directory
To get all the files in a directory.
String filenames[] = dir.list();
we can use this to retrieve files of specific extensions like the jar files from a directory.
public void testGetFiles() { File dir = new File("/test/test/file/demo"); ListOutputjarList = new ArrayList (); String filenames[] = dir.list(); for (int j = 0; j < filenames.length; j++) { String filename = filenames[j].toLowerCase(Locale.ENGLISH); if (!filename.endsWith(".jar")) continue; File file = new File(dir, filenames[j]); if (file.exists() && file.canRead()) { jarList.add(file.getName()); } } System.out.println(jarList); }
[el-api.jar, jasper-el.jar, jasper.jar, jsp-api.jar]
No comments:
Post a Comment