File Directory

0

In this article we will look into how we can use a File Object to read directory and its contents. We will also look into some subtle details related to File directory Object.

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.

    1. File exists

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.

    1. File is a directory

dir.isDirectory()

    1. Directory can be read

dir.canRead()

If a security manager exists and it doesn’t allow the specified file to be read then all the above three methods will throw a security exception. Likewise, it may be possible to start the JVM with special privileges that allow it to read files that are marked as unreadable. In such case, canRead may return true even though the file does not have read permissions.

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");
        List jarList = 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);
    }

Output

[el-api.jar, jasper-el.jar, jasper.jar, jsp-api.jar]

 

Share.

Leave A Reply