Module file
API
Declarations
ballerina/file Ballerina library
Overview
This module provides APIs, which perform file, file path, and directory operations, and a Directory Listener
, which is used to listen to a directory in the local file system.
This provides the interface to create, delete, rename the file/directory, retrieve metadata of the given file, and manipulate the filename paths in a way that is compatible according to the target file paths defined by the operating system.
The path of the file/directory needs to be defined with either forward slashes or back slashes depending on the operating system.
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.
onDelete: 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 regex module, see the below Functions.
Functions![](/images/permalink.svg)
basename![](/images/permalink.svg)
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![](/images/permalink.svg)
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![](/images/permalink.svg)
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![](/images/permalink.svg)
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![](/images/permalink.svg)
Creates a temporary file.
string tmpFile = check file:createTemp();
createTempDir![](/images/permalink.svg)
Creates a temporary directory.
string tmpDir = check file:createTempDir();
getAbsolutePath![](/images/permalink.svg)
Retrieves the absolute path from the provided location.
string absolutePath = check file:getAbsolutePath(<@untainted> "test.txt");
Parameters
- path string - String value of the file path free from potential malicious codes
getCurrentDir![](/images/permalink.svg)
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![](/images/permalink.svg)
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![](/images/permalink.svg)
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![](/images/permalink.svg)
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![](/images/permalink.svg)
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![](/images/permalink.svg)
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![](/images/permalink.svg)
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![](/images/permalink.svg)
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![](/images/permalink.svg)
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![](/images/permalink.svg)
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![](/images/permalink.svg)
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![](/images/permalink.svg)
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.
Enums![](/images/permalink.svg)
file: CopyOption![](/images/permalink.svg)
Represents options that can be used when copying files/directories
Members
file: DirOption![](/images/permalink.svg)
Represents options that can be used when creating or removing directories.
Members
file: NormOption![](/images/permalink.svg)
Represents the options that can be passed to normalizePath function.
Members
file: TestOption![](/images/permalink.svg)
Represents the options that can be passed to test function.
Members
Listeners![](/images/permalink.svg)
file: Listener![](/images/permalink.svg)
Represents the directory listener endpoint, which is used to listen to a directory in the local file system.
Constructor![](/images/permalink.svg)
Creates a new Directory listener.
init (ListenerConfig listenerConfig)
- listenerConfig ListenerConfig - The
ListenerConfig
record with the directory details
attach![](/images/permalink.svg)
Binds a service to the file:Listener
.
Parameters
- s service object {} - Type descriptor of the service
Return Type
- error? - () or else error upon failure to attach to the service
'start![](/images/permalink.svg)
function 'start() returns error?
Starts the file:Listener
.
Return Type
- error? - () or else error upon failure to start the listener
gracefulStop![](/images/permalink.svg)
function gracefulStop() returns error?
Stops the file:Listener
gracefully.
Return Type
- error? - () or else error upon failure to stop the listener
immediateStop![](/images/permalink.svg)
function immediateStop() returns error?
Stops the file:Listener
forcefully.
Return Type
- error? - () or else error upon failure to stop the listener
detach![](/images/permalink.svg)
function detach(service object {} s) returns error?
Stops listening to the directory and detaches the service from the file:Listener
.
Parameters
- s service object {} - Type descriptor of the service
Return Type
- error? - () or else error upon failure to detach to the service
Records![](/images/permalink.svg)
file: FileEvent![](/images/permalink.svg)
Represents an event which will trigger when there is a changes to listining direcotry.
Fields
- name string - Absolute file URI for triggerd event
- operation string - Triggered event action. This can be create, delete or modify
file: ListenerConfig![](/images/permalink.svg)
Represents configurations that required for 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![](/images/permalink.svg)
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![](/images/permalink.svg)
file: Error![](/images/permalink.svg)
Represents file system related errors.
file: FileNotFoundError![](/images/permalink.svg)
Represents an error that occurs when the file/directory does not exist at the given filepath.
file: FileSystemError![](/images/permalink.svg)
Represents an error that occurs when a file system operation fails.
file: GenericError![](/images/permalink.svg)
Represents generic error for filepath.
file: InvalidOperationError![](/images/permalink.svg)
Represents an error that occurs when a file system operation is denied due to invalidity.
file: InvalidPathError![](/images/permalink.svg)
Represents error occur when the given file path is invalid.
file: InvalidPatternError![](/images/permalink.svg)
Represent error occur when the given pattern is not a valid filepath pattern.
file: IOError![](/images/permalink.svg)
Represents IO error occur when trying to access the file at the given filepath.
file: NotLinkError![](/images/permalink.svg)
Represents error occur when the file at the given filepath is not a symbolic link.
file: PermissionError![](/images/permalink.svg)
Represents an error that occurs when a file system operation is denied, due to the absence of file permission.
file: RelativePathError![](/images/permalink.svg)
Represents an error that occurs when the given target filepath cannot be derived relative to the base filepath.
file: SecurityError![](/images/permalink.svg)
Represents security error occur when trying to access the file at the given filepath.
file: UNCPathError![](/images/permalink.svg)
Represents error occur in the UNC path.
Import
import ballerina/file;
Metadata
Released date: almost 3 years ago
Version: 1.0.0
Compatibility
Platform: java11
Ballerina version: slbeta3
Pull count
Total: 514391
Current verison: 1012
Weekly downloads