Interface FileSystem
Truffle files.- Since:
- 19.0
-
Nested Class Summary
Nested ClassesModifier and TypeInterfaceDescriptionstatic classA selector for determining whichFileSystemshould handle operations on a givenPath. -
Method Summary
Modifier and TypeMethodDescriptionstatic FileSystemallowInternalResourceAccess(FileSystem fileSystem) Decorates the givenfileSystemby an implementation that forwards access to the internal resources to the default file system.static FileSystemallowLanguageHomeAccess(FileSystem fileSystem) Deprecated.voidcheckAccess(Path path, Set<? extends AccessMode> modes, LinkOption... linkOptions) Checks existence and accessibility of a file.default voidcopy(Path source, Path target, CopyOption... options) Copies source file to target file.voidcreateDirectory(Path dir, FileAttribute<?>... attrs) Creates a directory.default voidcreateLink(Path link, Path existing) Creates a new link for an existing file.default voidcreateSymbolicLink(Path link, Path target, FileAttribute<?>... attrs) Creates a new symbolic link.voidDeletes a file.default CharsetgetEncoding(Path path) Returns an file encoding for given path.default longgetFileStoreBlockSize(Path path) Returns the number of bytes per block in the file store that contains the givenpath.default longgetFileStoreTotalSpace(Path path) Returns the size, in bytes, of the file store that contains the givenpath.default longReturns the number of unallocated bytes in the file store that contains the givenpath.default longgetFileStoreUsableSpace(Path path) Returns the number of bytes available to this Java virtual machine on the file store that contains the givenpath.default StringgetMimeType(Path path) Returns a MIME type for given path.default StringReturns the path separator used to separate filenames in a path list.default StringReturns the name separator used to separate names in a path string.default PathReturns the default temporary directory.default booleanisFileStoreReadOnly(Path path) Determines whether the file store containing the givenpathis read-only.default booleanisSameFile(Path path1, Path path2, LinkOption... options) Tests if the given paths refer to the same physical file.default voidmove(Path source, Path target, CopyOption... options) Moves (renames) source file to target file.newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) Opens or creates a file returning aSeekableByteChannelto access the file content.static FileSystemnewCompositeFileSystem(FileSystem fallbackFileSystem, FileSystem.Selector... delegates) Creates a compositeFileSystemthat delegates operations to the provideddelegates.static FileSystemCreates aFileSystemimplementation based on the host Java NIO.static FileSystemCreates aFileSystemthat denies all file operations except for path parsing.newDirectoryStream(Path dir, DirectoryStream.Filter<? super Path> filter) Returns directory entries.static FileSystemnewFileSystem(FileSystem fileSystem) Creates aFileSystemimplementation based on the given Java NIO filesystem.static FileSystemnewReadOnlyFileSystem(FileSystem fileSystem) Decorates the givenfileSystemby an implementation that makes the passedfileSystemread-only by forbidding all write operations.Parses a path from aString.Parses a path from anURI.readAttributes(Path path, String attributes, LinkOption... options) Reads a file's attributes as a bulk operation.default PathreadSymbolicLink(Path link) Reads the target of the symbolic link.default voidsetAttribute(Path path, String attribute, Object value, LinkOption... options) Sets a file's attribute.default voidsetCurrentWorkingDirectory(Path currentWorkingDirectory) Sets the current working directory.toAbsolutePath(Path path) Resolves given path to an absolute path.toRealPath(Path path, LinkOption... linkOptions) Returns the real (canonical) path of an existing file.
-
Method Details
-
parsePath
Parses a path from anURI.- Parameters:
uri- theURIto be converted toPath- Returns:
- the
Pathrepresenting givenURI - Throws:
UnsupportedOperationException- whenURIscheme is not supportedIllegalArgumentException- if preconditions on theurido not hold. The format of the URI isFileSystemspecific.- Since:
- 19.0
-
parsePath
- Parameters:
path- the string path to be converted toPath- Returns:
- the
Path - Throws:
UnsupportedOperationException- when theFileSystemsupports onlyURIIllegalArgumentException- if thepathstring cannot be converted to aPath- Since:
- 19.0
-
checkAccess
void checkAccess(Path path, Set<? extends AccessMode> modes, LinkOption... linkOptions) throws IOException Checks existence and accessibility of a file.- Parameters:
path- the path to the file to checkmodes- the access modes to check, possibly empty to check existence only.linkOptions- options determining how the symbolic links should be handled- Throws:
NoSuchFileException- if the file denoted by the path does not existIOException- in case of IO errorSecurityException- if thisFileSystemdenied the operation- Since:
- 19.0
-
createDirectory
Creates a directory.- Parameters:
dir- the directory to createattrs- the optional attributes to set atomically when creating the directory- Throws:
FileAlreadyExistsException- if a file on given path already existsIOException- in case of IO errorUnsupportedOperationException- if the attributes contain an attribute which cannot be set atomicallySecurityException- if thisFileSystemdenied the operation- Since:
- 19.0
-
delete
Deletes a file.- Parameters:
path- the path to the file to delete- Throws:
NoSuchFileException- if a file on given path does not existDirectoryNotEmptyException- if the path denotes a non empty directoryIOException- in case of IO errorSecurityException- if thisFileSystemdenied the operation- Since:
- 19.0
-
newByteChannel
SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException Opens or creates a file returning aSeekableByteChannelto access the file content.- Parameters:
path- the path to the file to openoptions- the options specifying how the file should be openedattrs- the optional attributes to set atomically when creating the new file- Returns:
- the created
SeekableByteChannel - Throws:
FileAlreadyExistsException- ifStandardOpenOption.CREATE_NEWoption is set and a file already exists on given pathIOException- in case of IO errorUnsupportedOperationException- if the attributes contain an attribute which cannot be set atomicallyIllegalArgumentException- in case of invalid options combinationSecurityException- if thisFileSystemdenied the operation- Since:
- 19.0
-
newDirectoryStream
DirectoryStream<Path> newDirectoryStream(Path dir, DirectoryStream.Filter<? super Path> filter) throws IOException Returns directory entries.- Parameters:
dir- the path to the directory to iterate entries forfilter- the filter- Returns:
- the new
DirectoryStream - Throws:
NotDirectoryException- when given path does not denote a directoryIOException- in case of IO errorSecurityException- if thisFileSystemdenied the operation- Since:
- 19.0
-
toAbsolutePath
Resolves given path to an absolute path.- Parameters:
path- the path to resolve, may be a non normalized path- Returns:
- an absolute
Path - Throws:
SecurityException- if thisFileSystemdenied the operation- Since:
- 19.0
-
toRealPath
Returns the real (canonical) path of an existing file.- Parameters:
path- the path to resolve, may be a non normalized pathlinkOptions- options determining how the symbolic links should be handled- Returns:
- an absolute canonical path
- Throws:
IOException- in case of IO errorSecurityException- if thisFileSystemdenied the operation- Since:
- 19.0
-
readAttributes
Map<String,Object> readAttributes(Path path, String attributes, LinkOption... options) throws IOException Reads a file's attributes as a bulk operation.- Parameters:
path- the path to file to read attributes forattributes- the attributes to read. Theattributesparameter has the form:[view-name:]attribute-list. The optionalview-namecorresponds toAttributeView.name()and determines the set of attributes, the default value is"basic". Theattribute-listis a comma separated list of attributes. If theattribute-listcontains'*'then all the attributes from given view are read.options- the options determining how the symbolic links should be handled- Returns:
- the
Mapcontaining the file attributes. The map's keys are attribute names, map's values are the attribute values. The map may contain a subset of required attributes in case when theFileSystemdoes not support some of the required attributes. - Throws:
UnsupportedOperationException- if the attribute view is not supported. At least the"basic"attribute view has to be supported by the file system.IllegalArgumentException- is theattribute-listis empty or contains an unknown attributeIOException- in case of IO errorSecurityException- if thisFileSystemdenied the operation- Since:
- 19.0
-
setAttribute
default void setAttribute(Path path, String attribute, Object value, LinkOption... options) throws IOException Sets a file's attribute.- Parameters:
path- the path to file to set an attribute toattribute- the attribute to set. Theattributeparameter has the form:[view-name:]attribute-name. The optionalview-namecorresponds toAttributeView.name()and determines the set of attributes, the default value is"basic". Theattribute-nameis a name of an attribute.value- the attribute valueoptions- the options determining how the symbolic links should be handled- Throws:
ClassCastException- ifvalueis not of the expected type orvalueis aCollectioncontaining element of a non expected typeUnsupportedOperationException- if the attribute view is not supported.IllegalArgumentException- is theattribute-nameis an unknown attribute orvaluehas an inappropriate valueIOException- in case of IO errorSecurityException- if thisFileSystemdenied the operation- Since:
- 19.0
-
copy
Copies source file to target file.- Parameters:
source- the path to file to copytarget- the path to the target fileoptions- the options specifying how the copy should be performed, seeStandardCopyOption- Throws:
UnsupportedOperationException- ifoptionscontains unsupported optionFileAlreadyExistsException- if the target path already exists and theoptionsdon't containStandardCopyOption.REPLACE_EXISTINGoptionDirectoryNotEmptyException- if theoptionscontainStandardCopyOption.REPLACE_EXISTINGbut thetargetis a non empty directoryIOException- in case of IO errorSecurityException- if thisFileSystemdenied the operation- Since:
- 19.0
-
move
Moves (renames) source file to target file.- Parameters:
source- the path to file to movetarget- the path to the target fileoptions- the options specifying how the move should be performed, seeStandardCopyOption- Throws:
UnsupportedOperationException- ifoptionscontains unsupported optionFileAlreadyExistsException- if the target path already exists and theoptionsdon't containStandardCopyOption.REPLACE_EXISTINGoptionDirectoryNotEmptyException- if theoptionscontainStandardCopyOption.REPLACE_EXISTINGbut thetargetis a non empty directoryAtomicMoveNotSupportedException- if theoptionscontainStandardCopyOption.ATOMIC_MOVEbut file cannot be moved atomicallyIOException- in case of IO errorSecurityException- if thisFileSystemdenied the operation- Since:
- 19.0
-
createLink
Creates a new link for an existing file.- Parameters:
link- the path to link to createexisting- the path to existing file- Throws:
UnsupportedOperationException- if links are not supported by file systemFileAlreadyExistsException- if a file on given link path already existsIOException- in case of IO errorSecurityException- if thisFileSystemdenied the operation- Since:
- 19.0
-
createSymbolicLink
default void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs) throws IOException Creates a new symbolic link.- Parameters:
link- the path to symbolic link to createtarget- the target path of the symbolic linkattrs- the optional attributes to set atomically when creating the new symbolic link- Throws:
UnsupportedOperationException- if symbolic links are not supported by file systemFileAlreadyExistsException- if a file on given link path already existsIOException- in case of IO errorSecurityException- if thisFileSystemdenied the operation- Since:
- 19.0
-
readSymbolicLink
Reads the target of the symbolic link.- Parameters:
link- the path to symbolic link to read- Returns:
- the
Pathrepresenting the symbolic link target - Throws:
UnsupportedOperationException- if symbolic links are not supported by file systemNotLinkException- if thelinkdoes not denote a symbolic linkIOException- in case of IO errorSecurityException- if thisFileSystemdenied the operation- Since:
- 19.0
-
setCurrentWorkingDirectory
Sets the current working directory. The current working directory is used to resolve non absolute paths inFileSystemoperations.- Parameters:
currentWorkingDirectory- the new current working directory- Throws:
UnsupportedOperationException- if setting of the current working directory is not supportedIllegalArgumentException- if thecurrentWorkingDirectoryis not a valid current working directorySecurityException- ifcurrentWorkingDirectoryis not readable- Since:
- 19.0
-
getSeparator
Returns the name separator used to separate names in a path string. The separator is used when creating path strings by invoking thetoString()method.- Returns:
- the name separator
- Since:
- 19.0
-
getPathSeparator
Returns the path separator used to separate filenames in a path list. On UNIX the path separator is':'. On Windows it's';'.- Returns:
- the path separator
- Since:
- 19.1.0
-
getMimeType
Returns a MIME type for given path. An optional operation forfilesystemimplementations which can provide MIME types in an efficient way.- Parameters:
path- the file to find a MIME type for- Returns:
- the MIME type or
nullif the MIME type is not recognized or thefilesystemdoes not support MIME type detection - Since:
- 19.0
-
getEncoding
Returns an file encoding for given path. An optional operation forfilesystemimplementations which can provide file encodings in an efficient way.- Parameters:
path- the file to find an file encoding for- Returns:
- the file encoding or
nullif the file encoding is not detected or thefilesystemdoes not support file encoding detection - Since:
- 19.0
-
getTempDirectory
-
isSameFile
Tests if the given paths refer to the same physical file. The default implementation firstly converts the paths into absolute paths. If the absolute paths are equal it returnstruewithout checking if the file exists. Otherwise, this method converts the paths into canonical representations and tests the canonical paths for equality. TheFileSystemmay re-implement the method with a more efficient test. When re-implemented the method must have the same security privileges as thetoAbsolutePathandtoRealPath.- Parameters:
path1- the path to the filepath2- the other pathoptions- the options determining how the symbolic links should be handled- Returns:
trueif the given paths refer to the same physical file- Throws:
IOException- in case of IO errorSecurityException- if thisFileSystemdenied the operation- Since:
- 20.2.0
-
getFileStoreTotalSpace
Returns the size, in bytes, of the file store that contains the givenpath. If the file store's size exceedsLong.MAX_VALUE,Long.MAX_VALUEis returned.- Parameters:
path- the path whose file store size is to be determined- Returns:
- the size of the file store in bytes
- Throws:
UnsupportedOperationException- if the file system does not support retrieving file store informationIOException- if an I/O error occurs while accessing the file storeSecurityException- if theFileSystemimplementation denied the operation- Since:
- 25.0.0
-
getFileStoreUnallocatedSpace
Returns the number of unallocated bytes in the file store that contains the givenpath. The returned value represents the raw free space on the storage device, regardless of access permissions or user quotas. If the number of unallocated bytes exceedsLong.MAX_VALUE,Long.MAX_VALUEis returned. Note that the value may be imprecise, as it can change at any time due to external I/O operations, including those performed outside this virtual machine.- Parameters:
path- the path whose file store is to be queried- Returns:
- the number of unallocated bytes
- Throws:
UnsupportedOperationException- if the file system does not support retrieving file store informationIOException- if an I/O error occurs while accessing the file storeSecurityException- if theFileSystemimplementation denied the operation- Since:
- 25.0.0
-
getFileStoreUsableSpace
Returns the number of bytes available to this Java virtual machine on the file store that contains the givenpath. UnlikegetFileStoreUnallocatedSpace(Path), this method accounts for operating system level restrictions, user quotas, and file system permissions, and therefore may return a smaller value. If the available space exceedsLong.MAX_VALUE,Long.MAX_VALUEis returned. Note that the returned value may be imprecise, as it can change at any time due to external I/O activity, including operations performed outside this virtual machine.- Parameters:
path- the path whose file store is to be queried- Returns:
- the number of usable bytes available to this Java virtual machine
- Throws:
UnsupportedOperationException- if the file system does not support retrieving file store informationIOException- if an I/O error occurs while accessing the file storeSecurityException- if theFileSystemimplementation denied the operation- Since:
- 25.0.0
-
getFileStoreBlockSize
Returns the number of bytes per block in the file store that contains the givenpath.- Parameters:
path- the path whose file store is to be queried- Returns:
- the block size
- Throws:
UnsupportedOperationException- if the file system does not support retrieving file store informationIOException- if an I/O error occurs while accessing the file storeSecurityException- if theFileSystemimplementation denied the operation- Since:
- 25.0.0
-
isFileStoreReadOnly
Determines whether the file store containing the givenpathis read-only.Note that even if the file store is not read-only, individual write operations may still be denied due to restrictions imposed by the
FileSystemimplementation, operating system level policies, user quotas, or file system permissions.- Parameters:
path- the path whose file store is to be queried- Throws:
UnsupportedOperationException- if the file system does not support retrieving file store informationIOException- if an I/O error occurs while accessing the file storeSecurityException- if theFileSystemimplementation denied the operation- Since:
- 25.0.0
-
newDefaultFileSystem
Creates aFileSystemimplementation based on the host Java NIO. The returned instance can be used as a delegate by a decoratingFileSystem.For an untrusted code execution, access to the host filesystem should be prevented either by using
IOAccess.NONEor annewFileSystem(java.nio.file.FileSystem)in-memory filesystem}. For more details on executing untrusted code, see the Polyglot Sandboxing Security Guide.The following example shows a
FileSystemlogging filesystem operations.class TracingFileSystem implements FileSystem { private static final Logger LOGGER = Logger.getLogger(TracingFileSystem.class.getName()); private final FileSystem delegate; TracingFileSystem() { this.delegate = FileSystem.newDefaultFileSystem(); } @Override public Path parsePath(String path) { return delegate.parsePath(path); } @Override public Path parsePath(URI uri) { return delegate.parsePath(uri); } @Override public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException { boolean success = false; try { SeekableByteChannel result = delegate.newByteChannel(path, options, attrs); success = true; return result; } finally { trace("newByteChannel", path, success); } } ... private void trace(String operation, Path path, boolean success) { LOGGER.log(Level.FINE, "The {0} request for the path {1} {2}.",new Object[] { operation, path, success ? "was successful" : "failed" }); } }- Since:
- 20.2.0
- See Also:
-
allowLanguageHomeAccess
Deprecated.Decorates the givenfileSystemby an implementation that forwards access to files in the language home to the default file system. The method is intended to be used by custom filesystem implementations with non default storage to allow guest languages to access files in the languages homes. As the returned filesystem uses a default file system to access files in the language home, thefileSystemhas to use the samePathtype,separatorandpath separatoras thedefault filesystem.- Throws:
IllegalArgumentException- when thefileSystemdoes not use the samePathtype or has a differentseparatororpath separatoras thedefault file system.- Since:
- 22.2
-
allowInternalResourceAccess
Decorates the givenfileSystemby an implementation that forwards access to the internal resources to the default file system. The method is intended to be used by custom filesystem implementations with non default storage to allow guest languages to access internal resources. As the returned filesystem uses a default file system to access internal resources, thefileSystemhas to use the samePathtype,separatorandpath separatoras thedefault filesystem.- Throws:
IllegalArgumentException- when thefileSystemdoes not use the samePathtype or has a differentseparatororpath separatoras thedefault file system.- Since:
- 24.0
- See Also:
-
newReadOnlyFileSystem
Decorates the givenfileSystemby an implementation that makes the passedfileSystemread-only by forbidding all write operations. This method can be used to make an existing file system, such as thedefault filesystem, read-only.- Since:
- 22.2
-
newFileSystem
Creates aFileSystemimplementation based on the given Java NIO filesystem. The returnedFileSystemdelegates all operations tofileSystem'sprovider.The following example shows how to configure
Contextso that languages read files from a prepared zip file.Path zipFile = Paths.get("filesystem.zip"); try (java.nio.file.FileSystem nioFs = FileSystems.newFileSystem(zipFile)) { IOAccess ioAccess = IOAccess.newBuilder().fileSystem(FileSystem.newFileSystem(nioFs)).build(); try (Context ctx = Context.newBuilder().allowIO(ioAccess).build()) { Value result = ctx.eval("js", "load('scripts/app.sh'); execute()"); } }- Since:
- 23.0
- See Also:
-
newDenyIOFileSystem
Creates aFileSystemthat denies all file operations except for path parsing. Any attempt to perform file operations such as reading, writing, or deletion will result in aSecurityExceptionbeing thrown.Typically, this file system does not need to be explicitly installed to restrict access to host file systems. Instead, use
Context.newBuilder().allowIO(IOAccess.NONE). This method is intended primarily for use as a fallback file system in acomposite file system.- Since:
- 24.2
-
newCompositeFileSystem
static FileSystem newCompositeFileSystem(FileSystem fallbackFileSystem, FileSystem.Selector... delegates) Creates a compositeFileSystemthat delegates operations to the provideddelegates. TheFileSystemof the firstdelegatewhoseFileSystem.Selector.test(Path)method accepts the path is used for the file system operation. If nodelegateaccepts the path, thefallbackFileSystemis used.The
fallbackFileSystemis responsible for parsingPathobjects. All provided file systems must use the samePathtype,separator, andpath separator. If any file system does not meet this requirement, anIllegalArgumentExceptionis thrown.The composite file system maintains its own notion of the current working directory and ensures that the
setCurrentWorkingDirectory(Path)method is not invoked on any of the delegates. When a request to set the current working directory is received, the composite file system verifies that the specified path corresponds to an existing directory by consulting either the appropriate delegate or thefallbackFileSystem. If an explicit current working directory has been set, the composite file system normalizes and resolves all relative paths to absolute paths prior to delegating operations. Conversely, if no explicit current working directory is set, the composite file system directly forwards the incoming path, whether relative or absolute, to the appropriate delegate. Furthermore, when an explicit current working directory is set, the composite file system does not delegatetoAbsolutePathoperations, as delegates do not maintain an independent notion of the current working directory. If the current working directory is unset,toAbsolutePathoperations are delegated to thefallbackFileSystem.Operations that are independent of path context, including
getTempDirectory,getSeparator, andgetPathSeparator, are handled exclusively by thefallbackFileSystem.- Throws:
IllegalArgumentException- if the file systems do not use the samePathtype,separator, orpath separator- Since:
- 24.2
-
allowInternalResourceAccess(FileSystem)}.