Path: blob/master/src/java.base/share/classes/java/nio/file/FileSystem.java
41159 views
/*1* Copyright (c) 2007, 2017, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.nio.file;2627import java.nio.file.attribute.*;28import java.nio.file.spi.FileSystemProvider;29import java.util.Set;30import java.io.Closeable;31import java.io.IOException;3233/**34* Provides an interface to a file system and is the factory for objects to35* access files and other objects in the file system.36*37* <p> The default file system, obtained by invoking the {@link FileSystems#getDefault38* FileSystems.getDefault} method, provides access to the file system that is39* accessible to the Java virtual machine. The {@link FileSystems} class defines40* methods to create file systems that provide access to other types of (custom)41* file systems.42*43* <p> A file system is the factory for several types of objects:44*45* <ul>46* <li><p> The {@link #getPath getPath} method converts a system dependent47* <em>path string</em>, returning a {@link Path} object that may be used48* to locate and access a file. </p></li>49* <li><p> The {@link #getPathMatcher getPathMatcher} method is used50* to create a {@link PathMatcher} that performs match operations on51* paths. </p></li>52* <li><p> The {@link #getFileStores getFileStores} method returns an iterator53* over the underlying {@link FileStore file-stores}. </p></li>54* <li><p> The {@link #getUserPrincipalLookupService getUserPrincipalLookupService}55* method returns the {@link UserPrincipalLookupService} to lookup users or56* groups by name. </p></li>57* <li><p> The {@link #newWatchService newWatchService} method creates a58* {@link WatchService} that may be used to watch objects for changes and59* events. </p></li>60* </ul>61*62* <p> File systems vary greatly. In some cases the file system is a single63* hierarchy of files with one top-level root directory. In other cases it may64* have several distinct file hierarchies, each with its own top-level root65* directory. The {@link #getRootDirectories getRootDirectories} method may be66* used to iterate over the root directories in the file system. A file system67* is typically composed of one or more underlying {@link FileStore file-stores}68* that provide the storage for the files. Theses file stores can also vary in69* the features they support, and the file attributes or <em>meta-data</em> that70* they associate with files.71*72* <p> A file system is open upon creation and can be closed by invoking its73* {@link #close() close} method. Once closed, any further attempt to access74* objects in the file system cause {@link ClosedFileSystemException} to be75* thrown. File systems created by the default {@link FileSystemProvider provider}76* cannot be closed.77*78* <p> A {@code FileSystem} can provide read-only or read-write access to the79* file system. Whether or not a file system provides read-only access is80* established when the {@code FileSystem} is created and can be tested by invoking81* its {@link #isReadOnly() isReadOnly} method. Attempts to write to file stores82* by means of an object associated with a read-only file system throws {@link83* ReadOnlyFileSystemException}.84*85* <p> File systems are safe for use by multiple concurrent threads. The {@link86* #close close} method may be invoked at any time to close a file system but87* whether a file system is <i>asynchronously closeable</i> is provider specific88* and therefore unspecified. In other words, if a thread is accessing an89* object in a file system, and another thread invokes the {@code close} method90* then it may require to block until the first operation is complete. Closing91* a file system causes all open channels, watch services, and other {@link92* Closeable closeable} objects associated with the file system to be closed.93*94* @since 1.795*/9697public abstract class FileSystem98implements Closeable99{100/**101* Initializes a new instance of this class.102*/103protected FileSystem() {104}105106/**107* Returns the provider that created this file system.108*109* @return The provider that created this file system.110*/111public abstract FileSystemProvider provider();112113/**114* Closes this file system.115*116* <p> After a file system is closed then all subsequent access to the file117* system, either by methods defined by this class or on objects associated118* with this file system, throw {@link ClosedFileSystemException}. If the119* file system is already closed then invoking this method has no effect.120*121* <p> Closing a file system will close all open {@link122* java.nio.channels.Channel channels}, {@link DirectoryStream directory-streams},123* {@link WatchService watch-service}, and other closeable objects associated124* with this file system. The {@link FileSystems#getDefault default} file125* system cannot be closed.126*127* @throws IOException128* If an I/O error occurs129* @throws UnsupportedOperationException130* Thrown in the case of the default file system131*/132@Override133public abstract void close() throws IOException;134135/**136* Tells whether or not this file system is open.137*138* <p> File systems created by the default provider are always open.139*140* @return {@code true} if, and only if, this file system is open141*/142public abstract boolean isOpen();143144/**145* Tells whether or not this file system allows only read-only access to146* its file stores.147*148* @return {@code true} if, and only if, this file system provides149* read-only access150*/151public abstract boolean isReadOnly();152153/**154* Returns the name separator, represented as a string.155*156* <p> The name separator is used to separate names in a path string. An157* implementation may support multiple name separators in which case this158* method returns an implementation specific <em>default</em> name separator.159* This separator is used when creating path strings by invoking the {@link160* Path#toString() toString()} method.161*162* <p> In the case of the default provider, this method returns the same163* separator as {@link java.io.File#separator}.164*165* @return The name separator166*/167public abstract String getSeparator();168169/**170* Returns an object to iterate over the paths of the root directories.171*172* <p> A file system provides access to a file store that may be composed173* of a number of distinct file hierarchies, each with its own top-level174* root directory. Unless denied by the security manager, each element in175* the returned iterator corresponds to the root directory of a distinct176* file hierarchy. The order of the elements is not defined. The file177* hierarchies may change during the lifetime of the Java virtual machine.178* For example, in some implementations, the insertion of removable media179* may result in the creation of a new file hierarchy with its own180* top-level directory.181*182* <p> When a security manager is installed, it is invoked to check access183* to the each root directory. If denied, the root directory is not returned184* by the iterator. In the case of the default provider, the {@link185* SecurityManager#checkRead(String)} method is invoked to check read access186* to each root directory. It is system dependent if the permission checks187* are done when the iterator is obtained or during iteration.188*189* @return An object to iterate over the root directories190*/191public abstract Iterable<Path> getRootDirectories();192193/**194* Returns an object to iterate over the underlying file stores.195*196* <p> The elements of the returned iterator are the {@link197* FileStore FileStores} for this file system. The order of the elements is198* not defined and the file stores may change during the lifetime of the199* Java virtual machine. When an I/O error occurs, perhaps because a file200* store is not accessible, then it is not returned by the iterator.201*202* <p> In the case of the default provider, and a security manager is203* installed, the security manager is invoked to check {@link204* RuntimePermission}{@code ("getFileStoreAttributes")}. If denied, then205* no file stores are returned by the iterator. In addition, the security206* manager's {@link SecurityManager#checkRead(String)} method is invoked to207* check read access to the file store's <em>top-most</em> directory. If208* denied, the file store is not returned by the iterator. It is system209* dependent if the permission checks are done when the iterator is obtained210* or during iteration.211*212* <p> <b>Usage Example:</b>213* Suppose we want to print the space usage for all file stores:214* <pre>215* for (FileStore store: FileSystems.getDefault().getFileStores()) {216* long total = store.getTotalSpace() / 1024;217* long used = (store.getTotalSpace() - store.getUnallocatedSpace()) / 1024;218* long avail = store.getUsableSpace() / 1024;219* System.out.format("%-20s %12d %12d %12d%n", store, total, used, avail);220* }221* </pre>222*223* @return An object to iterate over the backing file stores224*/225public abstract Iterable<FileStore> getFileStores();226227/**228* Returns the set of the {@link FileAttributeView#name names} of the file229* attribute views supported by this {@code FileSystem}.230*231* <p> The {@link BasicFileAttributeView} is required to be supported and232* therefore the set contains at least one element, "basic".233*234* <p> The {@link FileStore#supportsFileAttributeView(String)235* supportsFileAttributeView(String)} method may be used to test if an236* underlying {@link FileStore} supports the file attributes identified by a237* file attribute view.238*239* @return An unmodifiable set of the names of the supported file attribute240* views241*/242public abstract Set<String> supportedFileAttributeViews();243244/**245* Converts a path string, or a sequence of strings that when joined form246* a path string, to a {@code Path}. If {@code more} does not specify any247* elements then the value of the {@code first} parameter is the path string248* to convert. If {@code more} specifies one or more elements then each249* non-empty string, including {@code first}, is considered to be a sequence250* of name elements (see {@link Path}) and is joined to form a path string.251* The details as to how the Strings are joined is provider specific but252* typically they will be joined using the {@link #getSeparator253* name-separator} as the separator. For example, if the name separator is254* "{@code /}" and {@code getPath("/foo","bar","gus")} is invoked, then the255* path string {@code "/foo/bar/gus"} is converted to a {@code Path}.256* A {@code Path} representing an empty path is returned if {@code first}257* is the empty string and {@code more} does not contain any non-empty258* strings.259*260* <p> The parsing and conversion to a path object is inherently261* implementation dependent. In the simplest case, the path string is rejected,262* and {@link InvalidPathException} thrown, if the path string contains263* characters that cannot be converted to characters that are <em>legal</em>264* to the file store. For example, on UNIX systems, the NUL (\u0000)265* character is not allowed to be present in a path. An implementation may266* choose to reject path strings that contain names that are longer than those267* allowed by any file store, and where an implementation supports a complex268* path syntax, it may choose to reject path strings that are <em>badly269* formed</em>.270*271* <p> In the case of the default provider, path strings are parsed based272* on the definition of paths at the platform or virtual file system level.273* For example, an operating system may not allow specific characters to be274* present in a file name, but a specific underlying file store may impose275* different or additional restrictions on the set of legal276* characters.277*278* <p> This method throws {@link InvalidPathException} when the path string279* cannot be converted to a path. Where possible, and where applicable,280* the exception is created with an {@link InvalidPathException#getIndex281* index} value indicating the first position in the {@code path} parameter282* that caused the path string to be rejected.283*284* @param first285* the path string or initial part of the path string286* @param more287* additional strings to be joined to form the path string288*289* @return the resulting {@code Path}290*291* @throws InvalidPathException292* If the path string cannot be converted293*/294public abstract Path getPath(String first, String... more);295296/**297* Returns a {@code PathMatcher} that performs match operations on the298* {@code String} representation of {@link Path} objects by interpreting a299* given pattern.300*301* The {@code syntaxAndPattern} parameter identifies the syntax and the302* pattern and takes the form:303* <blockquote><pre>304* <i>syntax</i><b>:</b><i>pattern</i>305* </pre></blockquote>306* where {@code ':'} stands for itself.307*308* <p> A {@code FileSystem} implementation supports the "{@code glob}" and309* "{@code regex}" syntaxes, and may support others. The value of the syntax310* component is compared without regard to case.311*312* <p> When the syntax is "{@code glob}" then the {@code String}313* representation of the path is matched using a limited pattern language314* that resembles regular expressions but with a simpler syntax. For example:315*316* <table class="striped" style="text-align:left; margin-left:2em">317* <caption style="display:none">Pattern Language</caption>318* <thead>319* <tr>320* <th scope="col">Example321* <th scope="col">Description322* </tr>323* </thead>324* <tbody>325* <tr>326* <th scope="row">{@code *.java}</th>327* <td>Matches a path that represents a file name ending in {@code .java}</td>328* </tr>329* <tr>330* <th scope="row">{@code *.*}</th>331* <td>Matches file names containing a dot</td>332* </tr>333* <tr>334* <th scope="row">{@code *.{java,class}}</th>335* <td>Matches file names ending with {@code .java} or {@code .class}</td>336* </tr>337* <tr>338* <th scope="row">{@code foo.?}</th>339* <td>Matches file names starting with {@code foo.} and a single340* character extension</td>341* </tr>342* <tr>343* <th scope="row"><code>/home/*/*</code>344* <td>Matches <code>/home/gus/data</code> on UNIX platforms</td>345* </tr>346* <tr>347* <th scope="row"><code>/home/**</code>348* <td>Matches <code>/home/gus</code> and349* <code>/home/gus/data</code> on UNIX platforms</td>350* </tr>351* <tr>352* <th scope="row"><code>C:\\*</code>353* <td>Matches <code>C:\foo</code> and <code>C:\bar</code> on the Windows354* platform (note that the backslash is escaped; as a string literal in the355* Java Language the pattern would be <code>"C:\\\\*"</code>) </td>356* </tr>357* </tbody>358* </table>359*360* <p> The following rules are used to interpret glob patterns:361*362* <ul>363* <li><p> The {@code *} character matches zero or more {@link Character364* characters} of a {@link Path#getName(int) name} component without365* crossing directory boundaries. </p></li>366*367* <li><p> The {@code **} characters matches zero or more {@link Character368* characters} crossing directory boundaries. </p></li>369*370* <li><p> The {@code ?} character matches exactly one character of a371* name component.</p></li>372*373* <li><p> The backslash character ({@code \}) is used to escape characters374* that would otherwise be interpreted as special characters. The expression375* {@code \\} matches a single backslash and "\{" matches a left brace376* for example. </p></li>377*378* <li><p> The {@code [ ]} characters are a <i>bracket expression</i> that379* match a single character of a name component out of a set of characters.380* For example, {@code [abc]} matches {@code "a"}, {@code "b"}, or {@code "c"}.381* The hyphen ({@code -}) may be used to specify a range so {@code [a-z]}382* specifies a range that matches from {@code "a"} to {@code "z"} (inclusive).383* These forms can be mixed so [abce-g] matches {@code "a"}, {@code "b"},384* {@code "c"}, {@code "e"}, {@code "f"} or {@code "g"}. If the character385* after the {@code [} is a {@code !} then it is used for negation so {@code386* [!a-c]} matches any character except {@code "a"}, {@code "b"}, or {@code387* "c"}.388* <p> Within a bracket expression the {@code *}, {@code ?} and {@code \}389* characters match themselves. The ({@code -}) character matches itself if390* it is the first character within the brackets, or the first character391* after the {@code !} if negating.</p></li>392*393* <li><p> The {@code { }} characters are a group of subpatterns, where394* the group matches if any subpattern in the group matches. The {@code ","}395* character is used to separate the subpatterns. Groups cannot be nested.396* </p></li>397*398* <li><p> Leading period<code>/</code>dot characters in file name are399* treated as regular characters in match operations. For example,400* the {@code "*"} glob pattern matches file name {@code ".login"}.401* The {@link Files#isHidden} method may be used to test whether a file402* is considered hidden.403* </p></li>404*405* <li><p> All other characters match themselves in an implementation406* dependent manner. This includes characters representing any {@link407* FileSystem#getSeparator name-separators}. </p></li>408*409* <li><p> The matching of {@link Path#getRoot root} components is highly410* implementation-dependent and is not specified. </p></li>411*412* </ul>413*414* <p> When the syntax is "{@code regex}" then the pattern component is a415* regular expression as defined by the {@link java.util.regex.Pattern}416* class.417*418* <p> For both the glob and regex syntaxes, the matching details, such as419* whether the matching is case sensitive, are implementation-dependent420* and therefore not specified.421*422* @param syntaxAndPattern423* The syntax and pattern424*425* @return A path matcher that may be used to match paths against the pattern426*427* @throws IllegalArgumentException428* If the parameter does not take the form: {@code syntax:pattern}429* @throws java.util.regex.PatternSyntaxException430* If the pattern is invalid431* @throws UnsupportedOperationException432* If the pattern syntax is not known to the implementation433*434* @see Files#newDirectoryStream(Path,String)435*/436public abstract PathMatcher getPathMatcher(String syntaxAndPattern);437438/**439* Returns the {@code UserPrincipalLookupService} for this file system440* <i>(optional operation)</i>. The resulting lookup service may be used to441* lookup user or group names.442*443* <p> <b>Usage Example:</b>444* Suppose we want to make "joe" the owner of a file:445* <pre>446* UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService();447* Files.setOwner(path, lookupService.lookupPrincipalByName("joe"));448* </pre>449*450* @throws UnsupportedOperationException451* If this {@code FileSystem} does not does have a lookup service452*453* @return The {@code UserPrincipalLookupService} for this file system454*/455public abstract UserPrincipalLookupService getUserPrincipalLookupService();456457/**458* Constructs a new {@link WatchService} <i>(optional operation)</i>.459*460* <p> This method constructs a new watch service that may be used to watch461* registered objects for changes and events.462*463* @return a new watch service464*465* @throws UnsupportedOperationException466* If this {@code FileSystem} does not support watching file system467* objects for changes and events. This exception is not thrown468* by {@code FileSystems} created by the default provider.469* @throws IOException470* If an I/O error occurs471*/472public abstract WatchService newWatchService() throws IOException;473}474475476