My question has two parts - First, exactly what the title is - What is the Path.getNameCount() method actually counting? I read the little popup information that comes with it when you select a method in Eclipse, and I thought that this was an appropriate usage. This method I've created utilizing it is returning 5 as the int when it's run. Secondly, what I'm trying to do is return how many files are in the target directory so that I can run the other method I have to retrieve file names an appropriate number of times. If the getNameCount() method is not appropriate for this function, might you have any suggestions on how to accomplish the same ends?
//Global Variable for location of directory
Path dir = FileSystems.get("C:\\Users\\Heather\\Desktop\\Testing\\Testing2");
//Method for collecting the count of the files in the target directory.
public int Count()
{
int files=0;
files = dir.getNameCount();
return files;
}
}
It returns the number of elements in the path.
Check Oracle Docs
Example:-
Returns:
getNameCount()
returns number of elements in the path (subdirectories). For example, in Windows for "C:" that would be 0, and for "C:\a\b\c" - 3, in Unix-like systems, root ("/") would be at 0-level (getNameCount() == 0
) and "/home/user/abacaba" will be at the 3rd level, see javadocTo list directory you should use
DirectoryStream
: javadoc - perfect example is given here.As documented,
getNameCount()
returns:So in your case, the elements are
"Users"
,"Heather"
,"Desktop"
,"Testing"
and"Testing2"
- not the names of the file within the directory.To list the files in a directory, you can use
Files.list(Path)
(in Java 8+) orFiles.newDirectoryStream(Path)
(in Java 7+). Or you can convert to aFile
and use the "old school"File.listFiles()
method etc.