查看本类的 API文档回源码主页即时通讯网 - 即时通讯开发者社区!
1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package org.jboss.netty.channel;
17  
18  import org.jboss.netty.logging.InternalLogger;
19  import org.jboss.netty.logging.InternalLoggerFactory;
20  
21  import java.io.IOException;
22  import java.nio.channels.FileChannel;
23  import java.nio.channels.WritableByteChannel;
24  
25  public class DefaultFileRegion implements FileRegion {
26  
27      private static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultFileRegion.class);
28  
29      private final FileChannel file;
30      private final long position;
31      private final long count;
32      private final boolean releaseAfterTransfer;
33  
34      public DefaultFileRegion(FileChannel file, long position, long count) {
35          this(file, position, count, false);
36      }
37  
38      public DefaultFileRegion(FileChannel file, long position, long count, boolean releaseAfterTransfer) {
39          this.file = file;
40          this.position = position;
41          this.count = count;
42          this.releaseAfterTransfer = releaseAfterTransfer;
43      }
44  
45      public long getPosition() {
46          return position;
47      }
48  
49      public long getCount() {
50          return count;
51      }
52  
53      public boolean releaseAfterTransfer() {
54          return releaseAfterTransfer;
55      }
56  
57      public long transferTo(WritableByteChannel target, long position) throws IOException {
58          long count = this.count - position;
59          if (count < 0 || position < 0) {
60              throw new IllegalArgumentException(
61                      "position out of range: " + position +
62                      " (expected: 0 - " + (this.count - 1) + ')');
63          }
64          if (count == 0) {
65              return 0L;
66          }
67  
68          return file.transferTo(this.position + position, count, target);
69      }
70  
71      public void releaseExternalResources() {
72          try {
73              file.close();
74          } catch (IOException e) {
75              if (logger.isWarnEnabled()) {
76                  logger.warn("Failed to close a file.", e);
77              }
78          }
79      }
80  }