View Javadoc

1   package org.jboss.netty.channel;
2   
3   import java.io.IOException;
4   import java.nio.channels.FileChannel;
5   import java.nio.channels.WritableByteChannel;
6   
7   import org.jboss.netty.logging.InternalLogger;
8   import org.jboss.netty.logging.InternalLoggerFactory;
9   
10  public class DefaultFileRegion implements FileRegion {
11  
12      private static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultFileRegion.class);
13  
14      private final FileChannel file;
15      private final long position;
16      private final long count;
17  
18      public DefaultFileRegion(FileChannel file, long position, long count) {
19          this.file = file;
20          this.position = position;
21          this.count = count;
22      }
23  
24      public long getPosition() {
25          return position;
26      }
27  
28      public long getCount() {
29          return count;
30      }
31  
32      public long transferTo(WritableByteChannel target, long position) throws IOException {
33          long count = this.count - position;
34          if (count < 0 || position < 0) {
35              throw new IllegalArgumentException(
36                      "position out of range: " + position +
37                      " (expected: 0 - " + (this.count - 1) + ")");
38          }
39          if (count == 0) {
40              return 0L;
41          }
42  
43          return file.transferTo(this.position + position, count, target);
44      }
45  
46      public void releaseExternalResources() {
47          try {
48              file.close();
49          } catch (IOException e) {
50              logger.warn("Failed to close a file.", e);
51          }
52      }
53  }