What does getNameCount() actually count?

2019-08-03 15:52发布

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

3条回答
干净又极端
2楼-- · 2019-08-03 16:08

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
查看更多
Deceive 欺骗
3楼-- · 2019-08-03 16:10

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.

查看更多
戒情不戒烟
4楼-- · 2019-08-03 16:21

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.

查看更多
登录 后发表回答