Code example for FileChannel

Methods: close, truncate, write

0
      buffer.limit((int) ((buffer.limit() + ALIGN - 1) & ALIGN_NOT_MASK));
 
      assert (buffer.limit() & ALIGN_NOT_MASK) == buffer.limit() : "limit=" + buffer.limit() + " vs " + (buffer.limit() & ALIGN_NOT_MASK);
      assert (filePos & ALIGN_NOT_MASK) == filePos;
      //System.out.println(Thread.currentThread().getName() + ": dump to " + filePos + " limit=" + buffer.limit() + " fos=" + fos); 
      channel.write(buffer, filePos);
      filePos += bufferPos;
      bufferPos = 0;
      buffer.clear();
      //System.out.println("dump: done"); 
 
      // TODO: the case where we'd seek'd back, wrote an 
      // entire buffer, we must here read the next buffer; 
      // likely Lucene won't trip on this since we only 
      // write smallish amounts on seeking back 
    } 
 
    @Override 
    public long getFilePointer() { 
      return filePos + bufferPos;
    } 
 
    // TODO: seek is fragile at best; it can only properly 
    // handle seek & then change bytes that fit entirely 
    // within one buffer 
    @Override 
    public void seek(long pos) throws IOException {
      if (pos != getFilePointer()) {
        dump(); 
        final long alignedPos = pos & ALIGN_NOT_MASK;
        filePos = alignedPos;
        int n = (int) NativePosixUtil.pread(fos.getFD(), filePos, buffer);
        if (n < bufferSize) {
          buffer.limit(n);
        } 
        //System.out.println("seek refill=" + n); 
        final int delta = (int) (pos - alignedPos);
        buffer.position(delta);
        bufferPos = delta;
      } 
    } 
 
    @Override 
    public long length() throws IOException { 
      return fileLength;
    } 
 
    @Override 
    public void close() throws IOException { 
      if (isOpen) {
        isOpen = false;
        try { 
          dump(); 
        } finally { 
          try { 
            //System.out.println("direct close set len=" + fileLength + " vs " + channel.size() + " path=" + path); 
            channel.truncate(fileLength);
            //System.out.println("  now: " + channel.size()); 
          } finally { 
            try { 
              channel.close();
            } finally { 
              fos.close();
              //System.out.println("  final len=" + path.length()); 
            } 
          }