files - Finding Files, PathMacher

本文介绍Java NIO中Path类的resolve方法用于解决相对路径,Files类的createDirectory方法用于创建目录,以及FileSystem类的getPathMatcher方法用于匹配路径模式。通过示例展示了如何使用这些方法进行文件和目录的操作。

 

// files/Find.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {ExcludeFromGradle}

import java.nio.file.*;

public class Find {
  public static void main(String[] args) throws Exception {
    Path test = Paths.get("test");
    Directories.refreshTestDir();
    Directories.populateTestDir();
    System.out.println("test.resolve('dir.tmp'):" + test.resolve("dir.tmp"));
    // Creating a *directory*, not a file:
    Path p = Files.createDirectory(test.resolve("dir.tmp"));
    System.out.println("p:" + p);

    PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:**/*.{tmp,txt}");
    Files.walk(test).filter(matcher::matches).forEach(System.out::println);
    System.out.println("***************");

    PathMatcher matcher2 = FileSystems.getDefault().getPathMatcher("glob:*.tmp");
    Files.walk(test).map(Path::getFileName).filter(matcher2::matches).forEach(System.out::println);
    System.out.println("***************");

    Files.walk(test) // Only look for files
        .filter(Files::isRegularFile)
        .map(Path::getFileName)
        .filter(matcher2::matches)
        .forEach(System.out::println);
  }
}
/* My Output:
test.resolve('dir.tmp'):test/dir.tmp
p:test/dir.tmp
test\bag\foo\bar\baz\5208762845883213974.tmp
test\bag\foo\bar\baz\File.txt
test\bar\baz\bag\foo\7918367201207778677.tmp
test\bar\baz\bag\foo\File.txt
test\baz\bag\foo\bar\8016595521026696632.tmp
test\baz\bag\foo\bar\File.txt
test\dir.tmp
test\foo\bar\baz\bag\5832319279813617280.tmp
test\foo\bar\baz\bag\File.txt
***************
5208762845883213974.tmp
7918367201207778677.tmp
8016595521026696632.tmp
dir.tmp
5832319279813617280.tmp
***************
5208762845883213974.tmp
7918367201207778677.tmp
8016595521026696632.tmp
5832319279813617280.tmp
*/

**/ at the beginning of the glob expression means "all subdirectories"

matcher2 just uses *.tmp , which would ordinarily not match anything, but adding the map() operation reduces the full path to just the name at the end.

 

getPathMatcher

public abstract PathMatcher getPathMatcher(String syntaxAndPattern)

Returns a PathMatcher that performs match operations on the String representation of Path objects by interpreting a given pattern. The syntaxAndPattern parameter identifies the syntax and the pattern and takes the form:

 syntax:pattern
 

where ':' stands for itself.

FileSystem implementation supports the "glob" and "regex" syntaxes, and may support others. The value of the syntax component is compared without regard to case.

When the syntax is "glob" then the String representation of the path is matched using a limited pattern language that resembles regular expressions but with a simpler syntax. For example:

*.javaMatches 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:\bar on the Windows platform (note that the backslash is escaped; as a string literal in the Java Language the pattern would be "C:\\\\*")

The following rules are used to interpret glob patterns:

  • The * character matches zero or more characters of a name component without crossing directory boundaries.

  • The ** characters matches zero or more characters crossing directory boundaries.

  • The ? character matches exactly one character of a name component.

  • The backslash character (\) is used to escape characters that would otherwise be interpreted as special characters. The expression \\ matches a single backslash and "\{" matches a left brace for example.

  • The [ ] characters are a bracket expression that match a single character of a name component out of a set of characters. For example, [abc] matches "a""b", or "c". The hyphen (-) may be used to specify a range so [a-z] specifies a range that matches from "a" to "z" (inclusive). These forms can be mixed so [abce-g] matches "a""b""c""e""f" or "g". If the character after the [ is a ! then it is used for negation so [!a-c]matches any character except "a""b", or "c".

    Within a bracket expression the *? and \ characters match themselves. The (-) character matches itself if it is the first character within the brackets, or the first character after the ! if negating.

  • The { } characters are a group of subpatterns, where the group matches if any subpattern in the group matches. The "," character is used to separate the subpatterns. Groups cannot be nested.

  • Leading period/dot characters in file name are treated as regular characters in match operations. For example, the "*" glob pattern matches file name ".login". The Files.isHidden(java.nio.file.Path) method may be used to test whether a file is considered hidden.

  • All other characters match themselves in an implementation dependent manner. This includes characters representing any name-separators.

  • The matching of root components is highly implementation-dependent and is not specified.

When the syntax is "regex" then the pattern component is a regular expression as defined by the Pattern class.

For both the glob and regex syntaxes, the matching details, such as whether the matching is case sensitive, are implementation-dependent and therefore not specified.

Parameters:

syntaxAndPattern - The syntax and pattern

Returns:

A path matcher that may be used to match paths against the pattern

Throws:

IllegalArgumentException - If the parameter does not take the form: syntax:pattern

PatternSyntaxException - If the pattern is invalid

UnsupportedOperationException - If the pattern syntax is not known to the implementation

See Also:

Files.newDirectoryStream(Path,String)

 

resolve

Path resolve(Path other)

Resolve the given path against this path.

If the other parameter is an absolute path then this method trivially returns other. If other is an empty path then this method trivially returns this path. Otherwise this method considers this path to be a directory and resolves the given path against this path. In the simplest case, the given path does not have a root component, in which case this method joins the given path to this path and returns a resulting path that ends with the given path. Where the given path has a root component then resolution is highly implementation dependent and therefore unspecified.

Parameters:

other - the path to resolve against this path

Returns:

the resulting path

See Also:

relativize(java.nio.file.Path)

 

 

createDirectory

public static Path createDirectory(Path dir,
                                   FileAttribute<?>... attrs)
                            throws IOException

Creates a new directory. The check for the existence of the file and the creation of the directory if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the directory. The createDirectories method should be used where it is required to create all nonexistent parent directories first.

The attrs parameter is optional file-attributes to set atomically when creating the directory. Each attribute is identified by its name. If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.

Parameters:

dir - the directory to create

attrs - an optional list of file attributes to set atomically when creating the directory

Returns:

the directory

Throws:

UnsupportedOperationException - if the array contains an attribute that cannot be set atomically when creating the directory

FileAlreadyExistsException - if a directory could not otherwise be created because a file of that name already exists (optional specific exception)

IOException - if an I/O error occurs or the parent directory does not exist

SecurityException - In the case of the default provider, and a security manager is installed, the checkWrite method is invoked to check write access to the new directory.

references:

1. On Java 8 - Bruce Eckel

2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/files/Find.java

3. https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html

4. https://docs.oracle.com/javase/8/docs/api/java/nio/file/Path.html#resolve-java.nio.file.Path-

5. https://docs.oracle.com/javase/8/docs/api/java/nio/file/FileSystem.html#getPathMatcher-java.lang.String-

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值