Question

I have a java.io.File object and i don't know to which it corresponds. Using the isDirectory() method we can check whether it is a directory or not. A normal folder and a drive both returns true upon call to isDirectory()

How could i check if a File object is a drive or My Computer?

Was it helpful?

Solution

There are two ways, one is

File f=new File("C:\\");
if(f.toPath().getNameCount()==0) System.out.println(f+" is root");

getNameCount() method returns the no. of roots for a given File

toPath() method returns the java.nio.file.Path object for f. One more thing, you don't even need to import java.nio.file package here.

For instance if f=new File("C:\\Program Files"); then this returns 1 since there is only one root that is C:\\

A drive gets a name count of 0

My Computer cannot be represented as a File object. If you try to do,

File f=new File("C:\\").getParentFile(); you get null

Another way is (i dont recommend). Here we will have to use a loop, from performance perspective, it degrades performance and at the same time, this is lengthy as well.

File[] files=File.listRoots();
for(int i=0;i<files.length;i++)
{
  if(files[i].equals(f)){
  System.out.println(f+" is root");
  break;
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top