Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
875 views
in Technique[技术] by (71.8m points)

path - When to use ** (double star) in glob syntax within JAVA

Directly from this Java Oracle tutorial:

Two asterisks, **, works like * but crosses directory boundaries. This syntax is generally used for matching complete paths.

Could anybody do a real example out of it? What do they mean with "crosses directory boundary"? Crossing the directory boundary, I imagine something like checking the file from root to getNameCount()-1. Again a real example explaining the difference between * and ** in practice would be great.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The javadoc for FileSystem#getPathMatcher() has some pretty good examples and explanations

*.java Matches a path that represents a file name ending in .java 
*.*    Matches file names containing a dot 

*.{java,class}  Matches file names ending with .java or .class 
foo.?           Matches file names starting with foo. and a single character extension 
/home/*/*       Matches /home/gus/data on UNIX platforms 
/home/**        Matches /home/gus and /home/gus/data on UNIX platforms 
C:\*           Matches C:foo and C:ar on the Windows platform (note that the backslash is escaped; as a string literal in the Java Language the pattern would be "C:\\*")  

So /home/** would match /home/gus/data, but /home/* wouldn't.

/home/* is saying every file directly in the /home directory.

/home/** is saying every file in any directory inside /home.


Example of * vs **. Assuming your current working directory is /Users/username/workspace/myproject, then the following will only match the ./myproject file (directory).

PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:/Users/username/workspace/*");
Files.walk(Paths.get(".")).forEach((path) -> {
    path = path.toAbsolutePath().normalize();
    System.out.print("Path: " + path + " ");
    if (pathMatcher.matches(path)) {
        System.out.print("matched");
    }
    System.out.println();
});

If you use **, it will match all folders and files within that directory.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...