How to identify whether a given path is either file or directory in Java without using package?

Viewed 77

I'm creating a Java Program that identifies whether the given path is either file or directory without using any package.
What are the attributes that distinguishes between a file and a directory ?
Also, how does isFile() and isDirectory() method from java.io.File works at backend?

I tried separating from the extension, but found that directory name also can contain characters after period like directoryName.extension. I've some research on internet but failed to come with solid solution.

class FileCheck{
    public static void main(String[] args){
        boolean checkOne = isFile(C:\users);
        boolean checkTwo = isFile(C:\users\file.txt);
        boolean checkThree = isDirectory(C:\users);
        boolean checkFour = isDirectory(C:\users\file.txt);
    }
}

Don't get confused with isFile() and isDirectory() method. They are user created functions; not imported from java.io.File.

I expect if I pass C:\users as argument, it should return true value from isDirectory() function and when C:\users\file.txt, it should return false. Same logic applies for isFile() method.

2 Answers

There is no way of doing so.

It its pretty simple:

  • if the string you are passing as argument to this hypothetical methods doesn't exist in the file system ... then nobody can tell you if the name is a file or directory. Because it could easily be both
  • if the string denotes an existing thing: then simply use the Java interfaces that allow you to query it.

In other words: there is no way to know whether an arbitrary string represents a file or directory without checking the file system. And more importantly: there is no way to derive "file or directory" just from a "path string" alone.

What is a file and what is a directory ultimately depends on the file system. To distinguish between file and directory JVM will call the file system and get back the information. Knowing just the Path is not enough.

If you want to dig deeper it gets more complex. For example internally in Linux Ext4 filesystem everything is a file. Directory is just a special file with more information, as per Ext4 Disk Layout:

In an ext4 filesystem, a directory is more or less a flat file that maps an arbitrary byte string (usually ASCII) to an inode number on the filesystem. There can be many directory entries across the filesystem that reference the same inode number--these are known as hard links, and that is why hard links cannot reference files on other filesystems. As such, directory entries are found by reading the data block(s) associated with a directory file for the particular directory entry that is desired.

Related