2016-08-15 17 views
0

私はVertxを初めて使用しています。Vertxで非同期ファイルハンドラを書き込む方法

私はAPIを使って遊んでおり、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; 
    } 
} 

ハンドラで私を悩ます私は何をしていることである。ここでは

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クラスですそれはクラスのコンストラクタにあります。それを行うより良い方法はありますか?

答えて

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(); 
      } 
     }); 
    } 
} 
関連する問題