如何在Vertx中编写异步文件处理程序

时间:2016-08-15 11:25:57

标签: java asynchronous vert.x

我是Vertx的新手。

我正在使用API​​,我正在尝试编写FileSizeHandler。我不知道这是否是正确的做法,但我希望得到你的意见。

在我的代码中,我想使用这样的处理程序:

    public class MyVerticle extends AbstractVerticle {

            @Override
            public void start() throws Exception {
                getFileSize("./my_file.txt", event -> {
                 if(event.succeeded()){
                       Long result = event.result();
                       System.out.println("FileSize is " + result);
                } else {
                     System.out.println(event.cause().getLocalizedMessage());
                }
        });

     }  

    private void getFileSize(String filepath, Handler<AsyncResult<Long>> resultHandler){
        resultHandler.handle(new FileSizeHandler(filepath));
    }
}

这是我的FileSizeHandler课程:

public class FileSizeHandler implements AsyncResult<Long> {

    private boolean isSuccess;
    private Throwable cause;
    private Long result;

    public FileSizeHandler(String filePath){
        cause = null;
        isSuccess = false;
        result = 0L;

        try {
            result = Files.size(Paths.get(filePath));
            isSuccess = !isSuccess;
        } catch (IOException e) {
            cause = e;
        }

    }

    @Override
    public Long result() {
        return result;
    }

    @Override
    public Throwable cause() {
        return cause;
    }

    @Override
    public boolean succeeded() {
        return isSuccess;
    }

    @Override
    public boolean failed() {
        return !isSuccess;
    }
}

在处理程序中困扰我的是,我必须在类的构造函数中执行它。有没有更好的方法呢?

1 个答案:

答案 0 :(得分:2)

首先,你调用了你的类FileHandler,但事实并非如此。这是一个结果。 你可以在Vert.x中声明处理程序:

public class MyHandler implements Handler<AsyncResult<Long>> {

    @Override
    public void handle(AsyncResult<Long> event) {
        // Do some async code here
    }
}

现在,对于你所做的事情,有vertx.fileSystem()

public class MyVerticle extends AbstractVerticle {

    @Override
    public void start() throws Exception {

        vertx.fileSystem().readFile("./my_file.txt", (f) -> {
            if (f.succeeded()) {
                System.out.println(f.result().length());
            }
            else {
                f.cause().printStackTrace();
            }
        });
    }
}
相关问题