1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.handler.stream;
17
18 import static org.jboss.netty.buffer.ChannelBuffers.*;
19
20 import java.io.File;
21 import java.io.IOException;
22 import java.io.RandomAccessFile;
23
24 import org.jboss.netty.channel.FileRegion;
25
26
27
28
29
30
31
32
33 public class ChunkedFile implements ChunkedInput {
34
35 private final RandomAccessFile file;
36 private final long startOffset;
37 private final long endOffset;
38 private final int chunkSize;
39 private long offset;
40
41
42
43
44 public ChunkedFile(File file) throws IOException {
45 this(file, ChunkedStream.DEFAULT_CHUNK_SIZE);
46 }
47
48
49
50
51
52
53
54 public ChunkedFile(File file, int chunkSize) throws IOException {
55 this(new RandomAccessFile(file, "r"), chunkSize);
56 }
57
58
59
60
61 public ChunkedFile(RandomAccessFile file) throws IOException {
62 this(file, ChunkedStream.DEFAULT_CHUNK_SIZE);
63 }
64
65
66
67
68
69
70
71 public ChunkedFile(RandomAccessFile file, int chunkSize) throws IOException {
72 this(file, 0, file.length(), chunkSize);
73 }
74
75
76
77
78
79
80
81
82
83 public ChunkedFile(RandomAccessFile file, long offset, long length, int chunkSize) throws IOException {
84 if (file == null) {
85 throw new NullPointerException("file");
86 }
87 if (offset < 0) {
88 throw new IllegalArgumentException(
89 "offset: " + offset + " (expected: 0 or greater)");
90 }
91 if (length < 0) {
92 throw new IllegalArgumentException(
93 "length: " + length + " (expected: 0 or greater)");
94 }
95 if (chunkSize <= 0) {
96 throw new IllegalArgumentException(
97 "chunkSize: " + chunkSize +
98 " (expected: a positive integer)");
99 }
100
101 this.file = file;
102 this.offset = startOffset = offset;
103 endOffset = offset + length;
104 this.chunkSize = chunkSize;
105
106 file.seek(offset);
107 }
108
109
110
111
112 public long getStartOffset() {
113 return startOffset;
114 }
115
116
117
118
119 public long getEndOffset() {
120 return endOffset;
121 }
122
123
124
125
126 public long getCurrentOffset() {
127 return offset;
128 }
129
130 public boolean hasNextChunk() throws Exception {
131 return offset < endOffset && file.getChannel().isOpen();
132 }
133
134 public boolean isEndOfInput() throws Exception {
135 return !hasNextChunk();
136 }
137
138 public void close() throws Exception {
139 file.close();
140 }
141
142 public Object nextChunk() throws Exception {
143 long offset = this.offset;
144 if (offset >= endOffset) {
145 return null;
146 }
147
148 int chunkSize = (int) Math.min(this.chunkSize, endOffset - offset);
149 byte[] chunk = new byte[chunkSize];
150 file.readFully(chunk);
151 this.offset = offset + chunkSize;
152 return wrappedBuffer(chunk);
153 }
154 }