Vert.x Core is a high-performance, reactive application toolkit for the JVM providing fundamental building blocks for asynchronous I/O operations.
—
Comprehensive asynchronous file system operations including file I/O, directory management, file properties, and file watching capabilities.
Get the file system instance for performing file operations.
/**
* Get the file system instance
* @return FileSystem instance
*/
FileSystem fileSystem();
/**
* File System interface for asynchronous file operations
*/
interface FileSystem {
/**
* Read entire file into buffer
* @param path File path to read
* @return Future that completes with file contents
*/
Future<Buffer> readFile(String path);
/**
* Write buffer to file
* @param path File path to write
* @param data Data to write
* @return Future that completes when written
*/
Future<Void> writeFile(String path, Buffer data);
/**
* Copy a file
* @param from Source file path
* @param to Destination file path
* @return Future that completes when copied
*/
Future<Void> copy(String from, String to);
/**
* Copy a file with options
* @param from Source file path
* @param to Destination file path
* @param options Copy options
* @return Future that completes when copied
*/
Future<Void> copy(String from, String to, CopyOptions options);
/**
* Copy recursively
* @param from Source directory path
* @param to Destination directory path
* @return Future that completes when copied
*/
Future<Void> copyRecursive(String from, String to, boolean recursive);
/**
* Move/rename a file
* @param from Source file path
* @param to Destination file path
* @return Future that completes when moved
*/
Future<Void> move(String from, String to);
/**
* Move with options
* @param from Source file path
* @param to Destination file path
* @param options Copy options
* @return Future that completes when moved
*/
Future<Void> move(String from, String to, CopyOptions options);
/**
* Truncate a file
* @param path File path
* @param len New length
* @return Future that completes when truncated
*/
Future<Void> truncate(String path, long len);
/**
* Change file permissions
* @param path File path
* @param perms File permissions
* @return Future that completes when changed
*/
Future<Void> chmod(String path, String perms);
/**
* Change file permissions recursively
* @param path Directory path
* @param perms File permissions
* @param dirPerms Directory permissions
* @return Future that completes when changed
*/
Future<Void> chmodRecursive(String path, String perms, String dirPerms);
/**
* Change file owner
* @param path File path
* @param user User name
* @param group Group name
* @return Future that completes when changed
*/
Future<Void> chown(String path, String user, String group);
/**
* Get file properties
* @param path File path
* @return Future that completes with file properties
*/
Future<FileProps> props(String path);
/**
* Get link properties (don't follow symlinks)
* @param path File path
* @return Future that completes with file properties
*/
Future<FileProps> lprops(String path);
/**
* Create hard link
* @param link Link path
* @param existing Existing file path
* @return Future that completes when created
*/
Future<Void> link(String link, String existing);
/**
* Create symbolic link
* @param link Link path
* @param existing Existing file path
* @return Future that completes when created
*/
Future<Void> symlink(String link, String existing);
/**
* Delete/unlink a file
* @param path File path
* @return Future that completes when deleted
*/
Future<Void> unlink(String path);
/**
* Read symbolic link
* @param link Link path
* @return Future that completes with link target
*/
Future<String> readSymlink(String link);
/**
* Delete a file or directory
* @param path File or directory path
* @return Future that completes when deleted
*/
Future<Void> delete(String path);
/**
* Delete recursively
* @param path Directory path
* @param recursive Whether to delete recursively
* @return Future that completes when deleted
*/
Future<Void> deleteRecursive(String path, boolean recursive);
/**
* Create directory
* @param path Directory path
* @return Future that completes when created
*/
Future<Void> mkdir(String path);
/**
* Create directory with permissions
* @param path Directory path
* @param perms Directory permissions
* @return Future that completes when created
*/
Future<Void> mkdir(String path, String perms);
/**
* Create directories recursively
* @param path Directory path
* @return Future that completes when created
*/
Future<Void> mkdirs(String path);
/**
* Create directories with permissions
* @param path Directory path
* @param perms Directory permissions
* @return Future that completes when created
*/
Future<Void> mkdirs(String path, String perms);
/**
* Read directory
* @param path Directory path
* @return Future that completes with list of files
*/
Future<List<String>> readDir(String path);
/**
* Read directory with filter
* @param path Directory path
* @param filter Filename filter regex
* @return Future that completes with filtered list of files
*/
Future<List<String>> readDir(String path, String filter);
/**
* Open file for reading/writing
* @param path File path
* @param options Open options
* @return Future that completes with AsyncFile
*/
Future<AsyncFile> open(String path, OpenOptions options);
/**
* Create a new file
* @param path File path
* @return Future that completes when created
*/
Future<Void> createFile(String path);
/**
* Create file with permissions
* @param path File path
* @param perms File permissions
* @return Future that completes when created
*/
Future<Void> createFile(String path, String perms);
/**
* Check if file exists
* @param path File path
* @return Future that completes with existence check
*/
Future<Boolean> exists(String path);
/**
* Get file system properties
* @param path Path to check
* @return Future that completes with filesystem properties
*/
Future<FileSystemProps> fsProps(String path);
/**
* Create temporary directory
* @param prefix Directory name prefix
* @return Future that completes with temp directory path
*/
Future<String> createTempDirectory(String prefix);
/**
* Create temporary directory with attributes
* @param prefix Directory name prefix
* @param perms Directory permissions
* @param dir Parent directory
* @return Future that completes with temp directory path
*/
Future<String> createTempDirectory(String prefix, String perms, String dir);
/**
* Create temporary file
* @param prefix File name prefix
* @param suffix File name suffix
* @return Future that completes with temp file path
*/
Future<String> createTempFile(String prefix, String suffix);
/**
* Create temporary file with attributes
* @param prefix File name prefix
* @param suffix File name suffix
* @param perms File permissions
* @param dir Parent directory
* @return Future that completes with temp file path
*/
Future<String> createTempFile(String prefix, String suffix, String perms, String dir);
/**
* Watch a file or directory for changes
* @param path Path to watch
* @return Future that completes with file watcher
*/
Future<Watcher> watch(String path);
}Handle files asynchronously with streaming support and precise positioning.
/**
* Asynchronous file handle for reading/writing
*/
interface AsyncFile extends ReadStream<Buffer>, WriteStream<Buffer> {
/**
* Close the file
* @return Future that completes when closed
*/
Future<Void> close();
/**
* Write buffer to file
* @param buffer Data to write
* @return Future that completes when written
*/
Future<Void> write(Buffer buffer);
/**
* Write buffer at specific position
* @param buffer Data to write
* @param position Position to write at
* @return Future that completes when written
*/
Future<Void> write(Buffer buffer, long position);
/**
* Read from file into buffer
* @param buffer Buffer to read into
* @param offset Offset in buffer
* @param position Position in file
* @param length Number of bytes to read
* @return Future that completes with buffer
*/
Future<Buffer> read(Buffer buffer, int offset, long position, int length);
/**
* Flush data to storage
* @return Future that completes when flushed
*/
Future<Void> flush();
/**
* Set read position
* @param readPos New read position
* @return this for chaining
*/
AsyncFile setReadPos(long readPos);
/**
* Set write position
* @param writePos New write position
* @return this for chaining
*/
AsyncFile setWritePos(long writePos);
/**
* Get current read position
* @return Read position
*/
long getReadPos();
/**
* Get current write position
* @return Write position
*/
long getWritePos();
/**
* Get file size
* @return Future that completes with file size
*/
Future<Long> size();
/**
* Lock the file
* @return Future that completes with file lock
*/
Future<AsyncFileLock> lock();
/**
* Lock part of the file
* @param position Start position
* @param size Lock size
* @param shared Whether lock is shared
* @return Future that completes with file lock
*/
Future<AsyncFileLock> lock(long position, long size, boolean shared);
/**
* Try to lock the file (non-blocking)
* @return Future that completes with file lock or null
*/
Future<AsyncFileLock> tryLock();
/**
* Try to lock part of the file (non-blocking)
* @param position Start position
* @param size Lock size
* @param shared Whether lock is shared
* @return Future that completes with file lock or null
*/
Future<AsyncFileLock> tryLock(long position, long size, boolean shared);
}
/**
* File lock for controlling access
*/
interface AsyncFileLock {
/**
* Get lock position
* @return Lock position
*/
long position();
/**
* Get lock size
* @return Lock size
*/
long size();
/**
* Check if lock is shared
* @return true if shared
*/
boolean isShared();
/**
* Check if lock is valid
* @return true if valid
*/
boolean isValid();
/**
* Release the lock
* @return Future that completes when released
*/
Future<Void> release();
}Access file system metadata and properties.
/**
* File properties interface
*/
interface FileProps {
/**
* Get creation time
* @return Creation time
*/
Instant creationTime();
/**
* Get last access time
* @return Last access time
*/
Instant lastAccessTime();
/**
* Get last modified time
* @return Last modified time
*/
Instant lastModifiedTime();
/**
* Check if directory
* @return true if directory
*/
boolean isDirectory();
/**
* Check if other (not regular file, directory, or symlink)
* @return true if other
*/
boolean isOther();
/**
* Check if regular file
* @return true if regular file
*/
boolean isRegularFile();
/**
* Check if symbolic link
* @return true if symbolic link
*/
boolean isSymbolicLink();
/**
* Get file size
* @return File size in bytes
*/
long size();
/**
* Get file permissions
* @return File permissions string
*/
String permissions();
}
/**
* File system properties interface
*/
interface FileSystemProps {
/**
* Get total space
* @return Total space in bytes
*/
long totalSpace();
/**
* Get unallocated space
* @return Unallocated space in bytes
*/
long unallocatedSpace();
/**
* Get usable space
* @return Usable space in bytes
*/
long usableSpace();
}Configure file operations with various options.
/**
* Options for opening files
*/
class OpenOptions {
/**
* Set read mode
* @param read Whether to open for reading
* @return this for chaining
*/
OpenOptions setRead(boolean read);
/**
* Set write mode
* @param write Whether to open for writing
* @return this for chaining
*/
OpenOptions setWrite(boolean write);
/**
* Set create mode
* @param create Whether to create if doesn't exist
* @return this for chaining
*/
OpenOptions setCreate(boolean create);
/**
* Set create new mode
* @param createNew Whether to create only if doesn't exist
* @return this for chaining
*/
OpenOptions setCreateNew(boolean createNew);
/**
* Set delete on close
* @param deleteOnClose Whether to delete when closed
* @return this for chaining
*/
OpenOptions setDeleteOnClose(boolean deleteOnClose);
/**
* Set truncate existing
* @param truncateExisting Whether to truncate if exists
* @return this for chaining
*/
OpenOptions setTruncateExisting(boolean truncateExisting);
/**
* Set sparse file
* @param sparse Whether to create sparse file
* @return this for chaining
*/
OpenOptions setSparse(boolean sparse);
/**
* Set sync mode
* @param sync Whether to sync data and metadata
* @return this for chaining
*/
OpenOptions setSync(boolean sync);
/**
* Set dsync mode
* @param dsync Whether to sync data only
* @return this for chaining
*/
OpenOptions setDsync(boolean dsync);
/**
* Set file permissions
* @param perms File permissions
* @return this for chaining
*/
OpenOptions setPerms(String perms);
}
/**
* Options for copying files
*/
class CopyOptions {
/**
* Set replace existing
* @param replaceExisting Whether to replace existing files
* @return this for chaining
*/
CopyOptions setReplaceExisting(boolean replaceExisting);
/**
* Set copy attributes
* @param copyAttributes Whether to copy file attributes
* @return this for chaining
*/
CopyOptions setCopyAttributes(boolean copyAttributes);
/**
* Set no follow links
* @param nofollowLinks Whether to not follow symbolic links
* @return this for chaining
*/
CopyOptions setNofollowLinks(boolean nofollowLinks);
/**
* Set atomic move
* @param atomicMove Whether move should be atomic
* @return this for chaining
*/
CopyOptions setAtomicMove(boolean atomicMove);
}
/**
* File system configuration options
*/
class FileSystemOptions {
FileSystemOptions setClassPathResolvingEnabled(boolean classPathResolvingEnabled);
FileSystemOptions setFileCachingEnabled(boolean fileCachingEnabled);
}Watch files and directories for changes.
/**
* File watcher for monitoring changes
*/
interface Watcher {
/**
* Get the watched path
* @return Watched path
*/
String path();
/**
* Set event handler
* @param handler Handler for file events
* @return this for chaining
*/
Watcher handler(Handler<WatchEvent> handler);
/**
* Set exception handler
* @param handler Exception handler
* @return this for chaining
*/
Watcher exceptionHandler(Handler<Throwable> handler);
/**
* Close the watcher
* @return Future that completes when closed
*/
Future<Void> close();
}
/**
* File watch event
*/
interface WatchEvent {
/**
* Get event type
* @return Event type
*/
WatchEventType type();
/**
* Get file path
* @return File path
*/
String path();
}
/**
* Types of watch events
*/
enum WatchEventType {
CREATE, // File created
MODIFY, // File modified
DELETE // File deleted
}File system specific exceptions.
/**
* Exception for file system operation failures
*/
class FileSystemException extends VertxException {
public FileSystemException(String message);
public FileSystemException(String message, Throwable cause);
}Basic File Operations:
import io.vertx.core.file.FileSystem;
import io.vertx.core.buffer.Buffer;
FileSystem fs = vertx.fileSystem();
// Read file
fs.readFile("config.json").onSuccess(buffer -> {
System.out.println("File contents: " + buffer.toString());
}).onFailure(err -> {
System.err.println("Failed to read file: " + err.getMessage());
});
// Write file
Buffer data = Buffer.buffer("Hello World!");
fs.writeFile("output.txt", data).onSuccess(v -> {
System.out.println("File written successfully");
});
// Copy file
fs.copy("source.txt", "destination.txt").onSuccess(v -> {
System.out.println("File copied");
});
// Check if file exists
fs.exists("somefile.txt").onSuccess(exists -> {
if (exists) {
System.out.println("File exists");
} else {
System.out.println("File does not exist");
}
});Directory Operations:
// Create directory
fs.mkdir("newdir").onSuccess(v -> {
System.out.println("Directory created");
});
// Create nested directories
fs.mkdirs("path/to/nested/dir").onSuccess(v -> {
System.out.println("Nested directories created");
});
// Read directory contents
fs.readDir("mydir").onSuccess(files -> {
System.out.println("Directory contents:");
files.forEach(System.out::println);
});
// Read directory with filter
fs.readDir("logs", ".*\\.log").onSuccess(logFiles -> {
System.out.println("Log files:");
logFiles.forEach(System.out::println);
});
// Delete directory recursively
fs.deleteRecursive("olddir", true).onSuccess(v -> {
System.out.println("Directory deleted recursively");
});Async File Handling:
import io.vertx.core.file.AsyncFile;
import io.vertx.core.file.OpenOptions;
OpenOptions options = new OpenOptions()
.setRead(true)
.setWrite(true)
.setCreate(true);
fs.open("data.bin", options).onSuccess(file -> {
// Write data at specific position
Buffer data = Buffer.buffer("Hello");
file.write(data, 0).onSuccess(v -> {
System.out.println("Data written at position 0");
// Read data from specific position
Buffer readBuffer = Buffer.buffer(5);
file.read(readBuffer, 0, 0, 5).onSuccess(buffer -> {
System.out.println("Read: " + buffer.toString());
// Close file
file.close();
});
});
});
// Stream processing with async file
fs.open("largefile.dat", new OpenOptions().setRead(true))
.onSuccess(file -> {
file.handler(buffer -> {
// Process each chunk
processChunk(buffer);
});
file.endHandler(v -> {
System.out.println("File reading completed");
file.close();
});
});File Properties and Metadata:
// Get file properties
fs.props("myfile.txt").onSuccess(props -> {
System.out.println("File size: " + props.size());
System.out.println("Is directory: " + props.isDirectory());
System.out.println("Last modified: " + props.lastModifiedTime());
System.out.println("Permissions: " + props.permissions());
});
// Get filesystem properties
fs.fsProps("/").onSuccess(fsProps -> {
System.out.println("Total space: " + fsProps.totalSpace());
System.out.println("Usable space: " + fsProps.usableSpace());
System.out.println("Unallocated space: " + fsProps.unallocatedSpace());
});
// Change file permissions
fs.chmod("script.sh", "rwxr-xr-x").onSuccess(v -> {
System.out.println("Permissions changed");
});File Watching:
import io.vertx.core.file.WatchEvent;
import io.vertx.core.file.WatchEventType;
fs.watch("watchdir").onSuccess(watcher -> {
watcher.handler(event -> {
WatchEventType type = event.type();
String path = event.path();
switch (type) {
case CREATE:
System.out.println("File created: " + path);
break;
case MODIFY:
System.out.println("File modified: " + path);
break;
case DELETE:
System.out.println("File deleted: " + path);
break;
}
});
watcher.exceptionHandler(err -> {
System.err.println("Watcher error: " + err.getMessage());
});
// Stop watching after 30 seconds
vertx.setTimer(30000, id -> {
watcher.close().onSuccess(v -> {
System.out.println("Watcher closed");
});
});
});File Locking:
fs.open("shared.dat", new OpenOptions().setWrite(true).setRead(true))
.onSuccess(file -> {
// Lock entire file exclusively
file.lock().onSuccess(lock -> {
System.out.println("File locked exclusively");
// Perform operations on locked file
file.write(Buffer.buffer("Exclusive data")).onSuccess(v -> {
// Release lock
lock.release().onSuccess(released -> {
System.out.println("Lock released");
file.close();
});
});
});
});
// Try to acquire shared lock on part of file
fs.open("database.dat", new OpenOptions().setRead(true))
.onSuccess(file -> {
file.tryLock(1000, 500, true).onSuccess(lock -> {
if (lock != null) {
System.out.println("Acquired shared lock on bytes 1000-1500");
// Use the locked region
lock.release();
} else {
System.out.println("Could not acquire lock");
}
file.close();
});
});Install with Tessl CLI
npx tessl i tessl/maven-io-vertx--vertx-core