1 | /* |
2 | * Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0, |
3 | * and the EPL 1.0 (http://h2database.com/html/license.html). |
4 | * Initial Developer: H2 Group |
5 | */ |
6 | package org.h2.store.fs; |
7 | |
8 | import java.io.IOException; |
9 | import java.io.InputStream; |
10 | import java.nio.ByteBuffer; |
11 | import java.nio.channels.FileChannel; |
12 | |
13 | /** |
14 | * Allows to read from a file channel like an input stream. |
15 | */ |
16 | public class FileChannelInputStream extends InputStream { |
17 | |
18 | private final FileChannel channel; |
19 | private final boolean closeChannel; |
20 | |
21 | private ByteBuffer buffer; |
22 | private long pos; |
23 | |
24 | /** |
25 | * Create a new file object input stream from the file channel. |
26 | * |
27 | * @param channel the file channel |
28 | * @param closeChannel whether closing the stream should close the channel |
29 | */ |
30 | public FileChannelInputStream(FileChannel channel, boolean closeChannel) { |
31 | this.channel = channel; |
32 | this.closeChannel = closeChannel; |
33 | } |
34 | |
35 | @Override |
36 | public int read() throws IOException { |
37 | if (buffer == null) { |
38 | buffer = ByteBuffer.allocate(1); |
39 | } |
40 | buffer.rewind(); |
41 | int len = channel.read(buffer, pos++); |
42 | if (len < 0) { |
43 | return -1; |
44 | } |
45 | return buffer.get(0) & 0xff; |
46 | } |
47 | |
48 | @Override |
49 | public int read(byte[] b) throws IOException { |
50 | return read(b, 0, b.length); |
51 | } |
52 | |
53 | @Override |
54 | public int read(byte[] b, int off, int len) throws IOException { |
55 | ByteBuffer buff = ByteBuffer.wrap(b, off, len); |
56 | int read = channel.read(buff, pos); |
57 | if (read == -1) { |
58 | return -1; |
59 | } |
60 | pos += read; |
61 | return read; |
62 | } |
63 | |
64 | @Override |
65 | public void close() throws IOException { |
66 | if (closeChannel) { |
67 | channel.close(); |
68 | } |
69 | } |
70 | |
71 | } |