Module file
API
Declarations
ballerina/file Ballerina library
Overview
This module provides APIs to create, delete, rename the file/directory, retrieve metadata of the given file, and manipulate the file paths in a way that is compatible with the operating system, and a Directory Listener
, which is used to listen to the file changes in a directory in the local file system.
This also provides the following separators which are widely used in file path creation:
file:pathSeparator
: It is a character used to separate the parent directories that make up the path to a specific location. For windows, it’s ‘\’ and for UNIX it’s ‘/’file:pathListSeparator
: It is a character commonly used by the operating system to separate paths in the path list. For windows, it’s ‘;‘ and for UNIX it’s ‘:’
Directory listener
The file:Listener
is used to monitor all the files and subdirectories inside the specified directory.
A Listener
endpoint can be defined using the mandatory path
parameter and the optional recursive
parameter as follows.
listener file:Listener inFolder = new ({ path: "<The directory path>", recursive: false });
If the listener needs to monitor subdirectories of the given directory, recursive
needs to be set to true
. The default value of this is false
.
A Service
has the defined remote methods with the file:FileEvent
and can be exposed via a Listener
endpoint.
When there are changes in the listening directory, the file:FileEvent
will be triggered with the action of the file
such as creating, modifying, or deleting.
The remote methods supported by the Service
are as follows.
onCreate: This method is invoked once a new file is created in the listening directory.
onDelete: This method is invoked once an existing file is deleted from the listening directory.
onModify: This method is invoked once an existing file is modified in the listening directory.
The following code sample shows how to create a Service
with the onCreate
remote method and attach it to the above Listener
endpoint:
service "localObserver" on inFolder { remote function onCreate(file:FileEvent m) { string msg = "Create: " + m.name; log:printInfo(msg); } }
For information on the operations, which you can perform with the file module, see the below Functions.
Functions
basename
Retrieves the base name of the file from the provided location, which is the last element of the path. Trailing path separators are removed before extracting the last element.
string name = check file:basename("/A/B/C.txt");
Parameters
- path string - String value of file path
copy
function copy(string sourcePath, string destinationPath, CopyOption... options) returns Error?
Copy the file/directory in the old path to the new path.
check file:copy("/A/B/C", "/A/B/D", true);
Parameters
- sourcePath string - String value of the old file path
- destinationPath string - String value of the new file path
- options CopyOption... - Parameter to denote how the copy operation should be done. Supported options are,
REPLACE_EXISTING
- Replace the target path if it already exists,COPY_ATTRIBUTES
- Copy the file attributes as well to the target,NO_FOLLOW_LINKS
- If source is a symlink, only the link is copied, not the target of the link.
Return Type
- Error? - An
file:Error
if failed to copy
create
Creates a file in the specified file path. Truncates if the file already exists in the given path.
check file:create("bar.txt");
Parameters
- path string - String value of the file path
Return Type
- Error? - A
file:Error
if file creation failed
createDir
Creates a new directory with the specified name.
check file:createDir("foo/bar");
Parameters
- dir string - Directory name
- option DirOption (default NON_RECURSIVE) - Indicates whether the
createDir
should create non-existing parent directories. The default is only to create the given current directory.
Return Type
- Error? - A
file:Error
if the directory creation failed
createTemp
Creates a temporary file.
string tmpFile = check file:createTemp();
createTempDir
Creates a temporary directory.
string tmpDir = check file:createTempDir();
getAbsolutePath
Retrieves the absolute path from the provided location.
string absolutePath = check file:getAbsolutePath("test.txt");
Parameters
- path string - String value of the file path free from potential malicious codes
getCurrentDir
function getCurrentDir() returns string
Returns the current working directory.
string dirPath = file:getCurrentDir();
Return Type
- string - Current working directory or else an empty string if the current working directory cannot be determined
getMetaData
Returns the metadata information of the file specified in the file path.
file:MetaData result = check file:getMetaData("foo/bar.txt");
Parameters
- path string - String value of the file path.
isAbsolutePath
Reports whether the path is absolute. A path is absolute if it is independent of the current directory. On Unix, a path is absolute if it starts with the root. On Windows, a path is absolute if it has a prefix and starts with the root: c:\windows.
boolean isAbsolute = check file:isAbsolutePath("/A/B/C");
Parameters
- path string - String value of the file path
joinPath
Joins any number of path elements into a single path.
string path = check file:joinPath("/", "foo", "bar");
Parameters
- parts string... - String values of the file path parts
normalizePath
function normalizePath(string path, NormOption option) returns string|Error
Normalizes a path value.
string normalizedPath = check file:normalizePath("foo/../bar", file:CLEAN);
Parameters
- path string - String value of the file path
- option NormOption - Normalization option. Supported options are,
CLEAN
- Get the shortest path name equivalent to the given path by eliminating multiple separators, '.', and '..',SYMLINK
- Evaluate a symlink,NORMCASE
- Normalize the case of a pathname. On windows, all the characters are converted to lowercase and "/" is converted to "\".
parentPath
Returns the enclosing parent directory. If the path is empty, parent returns ".". The returned path does not end in a separator unless it is the root directory.
string parentPath = check file:parentPath("/A/B/C.txt");
Parameters
- path string - String value of the file/directory path
readDir
Reads the directory and returns a list of metadata of files and directories inside the specified directory.
file:MetaData[] results = check file:readDir("foo/bar");
Parameters
- path string - String value of the directory path
relativePath
Returns a relative path, which is logically equivalent to the target path when joined to the base path with an intervening separator. An error is returned if the target path cannot be made relative to the base path.
string relative = check file:relativePath("a/b/e", "a/c/d");
remove
Removes the specified file or directory.
check file:remove("foo/bar.txt");
Parameters
- path string - String value of the file/directory path
- option DirOption (default NON_RECURSIVE) - Indicates whether the
remove
should recursively remove all the files inside the given directory
Return Type
- Error? - An
file:Error
if failed to remove
rename
Renames(Moves) the old path with the new path. If the new path already exists and it is not a directory, this replaces the file.
check file:rename("/A/B/C", "/A/B/D");
Parameters
- oldPath string - String value of the old file path
- newPath string - String value of the new file path
Return Type
- Error? - An
file:Error
if failed to rename
splitPath
Splits a list of paths joined by the OS-specific path separator.
string[] parts = check file:splitPath("/A/B/C");
Parameters
- path string - String value of the file path
test
function test(string path, TestOption testOption) returns boolean|Error
Tests a file path against a test condition .
boolean result = check file:test("foo/bar.txt", file:EXISTS);
Parameters
- path string - String value of the file path
- testOption TestOption - The option to be tested upon the path. Supported options are,
EXISTS
- Test whether a file path exists,IS_DIR
- Test whether a file path is a directory,IS_SYMLINK
- Test whether a file path is a symlink,READABLE
- Test whether a file path is readable,WRITABLE
- Test whether a file path is writable.
Service types
file: Service
Represents a File service.
Enums
file: CopyOption
Represents options that can be used when copying files/directories
Members
file: DirOption
Represents options that can be used when creating or removing directories.
Members
file: NormOption
Represents the options that can be passed to the normalizePath
function.
Members
file: TestOption
Represents the options that can be passed to the test function.
Members
Variables
Listeners
file: Listener
Represents the directory listener endpoint, which is used to listen to a directory in the local file system.
Constructor
Creates a new Directory listener.
init (ListenerConfig listenerConfig)
- listenerConfig ListenerConfig - The
ListenerConfig
record with the directory details
attach
Binds a service to the file:Listener
.
Parameters
- s Service - Type descriptor of the service
Return Type
- error? - () or else error upon failure to attach to the service
'start
function 'start() returns error?
Starts the file:Listener
.
Return Type
- error? - () or else error upon failure to start the listener
gracefulStop
function gracefulStop() returns error?
Stops the file:Listener
gracefully.
Return Type
- error? - () or else error upon failure to stop the listener
immediateStop
function immediateStop() returns error?
Stops the file:Listener
forcefully.
Return Type
- error? - () or else error upon failure to stop the listener
detach
Stops listening to the directory and detaches the service from the file:Listener
.
Parameters
- s Service - Type descriptor of the service
Return Type
- error? - () or else error upon failure to detach to the service
Records
file: FileEvent
Represents an event, which will trigger when there is a change to the listening directory.
Fields
- name string - Absolute file URI for triggered event
- operation string - Triggered event action. This can be create, delete or modify
file: ListenerConfig
Represents the configurations that are required for a directory listener.
Fields
- path string - Directory path which need to listen
- recursive boolean(default false) - Recursively monitor all sub folders or not in the given direcotry path
file: MetaData
Metadata record contains metadata information of a file. This record is returned by getMetaData function.
Fields
- absPath string - Absolute path of the file
- size int - Size of the file (in bytes)
- modifiedTime Utc - The last modified time of the file
- dir boolean - Whether the file is a directory or not
- readable boolean - Whether the file is readable or not
- writable boolean - Whether the file is writable or not
Errors
file: Error
Represents file system related errors.
file: FileNotFoundError
Represents an error, which occurs when the file/directory does not exist in the given file path.
file: FileSystemError
Represents an error that occurs when a file system operation fails.
file: GenericError
Represents a generic error for the file path.
file: InvalidOperationError
Represents an error that occurs when a file system operation is denied due to invalidity.
file: InvalidPathError
Represents an error, which occurs when the given file path is invalid.
file: InvalidPatternError
Represents an error, which occurs when the given pattern is not a valid file path pattern.
file: IOError
Represents an IO error, which occurs when trying to access the file in the given file path.
file: NotLinkError
Represents an error, which occurs when the file in the given file path is not a symbolic link.
file: PermissionError
Represents an error that occurs when a file system operation is denied, due to the absence of file permission.
file: RelativePathError
Represents an error, which occurs when the given target file path cannot be derived relative to the base file path.
file: SecurityError
Represents a security error, which occurs when trying to access the file in the given file path.
file: UNCPathError
Represents an error, which occurs in the UNC path.
Import
import ballerina/file;
Metadata
Released date: over 1 year ago
Version: 1.8.0
License: Apache-2.0
Compatibility
Platform: java11
Ballerina version: 2201.7.0
GraalVM compatible: Yes
Pull count
Total: 524969
Current verison: 20736
Weekly downloads
Keywords
file
path
directory
filepath
Contributors