问题
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;
}
}
回答1:
As documented, getNameCount()
returns:
the number of elements in the path, or 0 if this path only represents a root component
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+) or Files.newDirectoryStream(Path) (in Java 7+). Or you can convert to a File
and use the "old school" File.listFiles() method etc.
回答2:
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 javadoc
To list directory you should use DirectoryStream
: javadoc - perfect example is given here.
回答3:
It returns the number of elements in the path.
Check Oracle Docs
Example:-
Path path = Paths.get("C:", "tutorial/Java/JavaFX", "Topic.txt");
System.out.println(path.getNameCount());
Returns:
4
来源:https://stackoverflow.com/questions/24264942/what-does-getnamecount-actually-count