Asynchronous non-blocking File Reader and Writer library for Java
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src
.gitignore
LICENSE
README.md
pom.xml

README.md

AsyncFileRw

Build Status Maven Central Version Coverage Status

The AsyncFiles class allows Java applications to easily read/write files asynchronously and without blocking. This is an equivalent to the standard JDK Files class but using non-blocking IO. In section Usage we present some examples using the AsyncFiles class side by side with the corresponding blocking version of Files.

Installation

First, in order to include it to your Maven project, simply add this dependency:

<dependency>
    <groupId>com.github.javasync</groupId>
    <artifactId>AsyncFileRw</artifactId>
    <version>1.0.0</version>
</dependency>

To add a dependency using Gradle:

dependencies {
  compile 'com.github.javasync:AsyncFileRw:1.0.0'
}

Usage

Writing lines into a file


Path path = Paths.get("output.txt")
List<String> data = asList("super", "brave", "isel", "gain");
AsyncFiles
    .write(path, data)
    .join(); // block if you want to wait for write completion
            

Path path = Paths.get("output.txt")
List<String> data = asList("super", "brave", "isel", "gain");
Files.write(path, data);
 
 
            

Reading all bytes from one file and writing to another


Path in = Paths.get("input.txt");
Path out = Paths.get("output.txt");
AsyncFiles
        .readAllBytes(in)
        .thenCompose(bytes -> AsyncFiles.writeBytes(out, bytes))
        .join(); // block if you want to wait for write completion
            

Path in = Paths.get("input.txt");
Path out = Paths.get("output.txt");
byte[] bytes = Files.readAllBytes(in);
Files.write(out, bytes);
 
 
            

Printing all lines from a file


String path = "input.txt";
AsyncFiles
    .lines(path)
    .subscribe(new Subscriber() {
        public void onSubscribe(Subscription s) { }
        public void onNext(String line) {
            out.println(line)
        }
        public void onError(Throwable throwable) { }
        public void onComplete() {}
    });
            

Path path = Paths.get("input.txt");
Files
    .lines(path)
    .forEach(out::println)
            

The AsyncFiles::lines() returns a reactive Publisher which is compatible with Reactor or RxJava streams. Thus we can use their utility methods to easily operate on the result of AsyncFiles::lines(). For example, with the utility methods of Reactor Flux we can rewrite the previous sample as:

Flux
    .from(AsyncFiles.lines(path))
    .doOnNext(out::println)
    .blockLast(); // block if you want to wait for completion