Using the file system with Vert.x
The Vert.x FileSystem
object provides many operations for manipulating the file system.
There is one file system object per Vert.x instance, and you obtain it with fileSystem
.
A blocking and a non blocking version of each operation is provided.
The non blocking versions take a handler which is called when the operation completes or an error occurs.
Here’s an example of asynchronously copying a file:
def fs = vertx.fileSystem()
// Copy file from foo.txt to bar.txt
fs.copy("foo.txt", "bar.txt", { res ->
if (res.succeeded()) {
// Copied ok!
} else {
// Something went wrong
}
})
The blocking versions are named and return the results or throw exceptions directly.
In many cases, depending on the operating system and file system,some of the potentially blocking operations can return quickly, which is why we provide them, but it’s highly recommended that you test how long they take to return in your particular application before using them from an event loop, so as not to break the Golden Rule.
Here’s the copy using the blocking API:
def fs = vertx.fileSystem()
// Copy file from foo.txt to bar.txt synchronously
fs.copyBlocking("foo.txt", "bar.txt")
Many operations exist to copy, move, truncate, chmod and many other file operations.
We won’t list them all here, please consult the API docs
for the full list.
Asynchronous files
Vert.x provides an asynchronous file abstraction that allows you to manipulate a file on the file system
You open an AsyncFile
as follows:
def options = [:]
fileSystem.open("myfile.txt", options, { res ->
if (res.succeeded()) {
def file = res.result()
} else {
// Something went wrong!
}
})
TODO