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;
}
}