示例#1
0
  private Interfaces.Callback<Long> makeReader(
      AsynchronousFileChannel channel,
      boolean autoClose,
      long position,
      Interfaces.Callback<ByteBuffer> cb) {

    return (err, fileSize) -> {
      if (fileSize > Integer.MAX_VALUE) {
        String message =
            "File size "
                + fileSize
                + " exceeds maximum allowed value. Use fs.createReadStream to read big files.";
        eventLoop.runTicket(() -> cb.invoke(new IOException(message), null));
        return;
      }

      if (err != null) {
        eventLoop.runTicket(() -> cb.invoke(err, null));
        return;
      }

      eventLoop.addBackgroundOperation();

      ByteBuffer buffer = ByteBuffer.allocate(fileSize.intValue());

      CompletionHandler<Integer, ByteBuffer> completion =
          new ReadCompletionHandler(cb, channel, autoClose);
      channel.read(buffer, position, buffer, completion);
    };
  }
示例#2
0
  public void readFile(String path, Interfaces.Callback<ByteBuffer> cb) {
    Path file = Paths.get(path);
    AsynchronousFileChannel channel = openFileChannel(cb, file);

    if (channel == null) {
      return;
    }

    eventLoop.runInBackground(() -> Files.size(file), makeReader(channel, true, 0, cb));
  }
示例#3
0
  private <T> AsynchronousFileChannel openFileChannel(Interfaces.Callback<T> cb, Path file) {
    AsynchronousFileChannel channel = null;
    try {
      channel = AsynchronousFileChannel.open(file);

    } catch (IOException e) {

      eventLoop.runTicket(() -> cb.invoke(new RuntimeException(e), null));
    }

    return channel;
  }
示例#4
0
  public void readFile(String path, String encoding, Interfaces.Callback<String> cb) {
    Path file = Paths.get(path);
    AsynchronousFileChannel channel = openFileChannel(cb, file);

    if (channel == null) {
      return;
    }
    eventLoop.runInBackground(
        () -> Files.size(file),
        makeReader(
            channel,
            true,
            0,
            (err, buffer) -> {
              Charset charset = Charset.forName(encoding);
              cb.invoke(null, new String(buffer.array(), 0, buffer.position(), charset));
            }));
  }