File D:\maven-qcr-plugin-testsunitaires\qcr4java\h2-1.3.170-sources\target\site\qc\lecode\store\fs\FileChannelInputStream.java.html

1 /*
2 * Copyright 2004-2011 H2 Group. Multiple-Licensed under the H2 License,
3 * Version 1.0, and under the Eclipse Public License, Version 1.0
4 * (http://h2database.com/html/license.html).
5 * Initial Developer: H2 Group
6 */
7 package org.h2.store.fs;
8
9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.nio.ByteBuffer;
12 import java.nio.channels.FileChannel;
13
14 /**
15 * Allows to read from a file channel like an input stream.
16 */
17 public class FileChannelInputStream extends InputStream {
18
19 private final FileChannel channel;
20 private final byte[] buffer = { 0 };
21
22 /**
23 * Create a new file object input stream from the file channel.
24 *
25 * @param channel the file channel
26 */
27 public FileChannelInputStream(FileChannel channel) {
28 this.channel = channel;
29 }
30
31 public int read() throws IOException {
32 if (channel.position() >= channel.size()) {
33 return -1;
34 }
35 FileUtils.readFully(channel, ByteBuffer.wrap(buffer));
36 return buffer[0] & 0xff;
37 }
38
39 public int read(byte[] b) throws IOException {
40 return read(b, 0, b.length);
41 }
42
43 public int read(byte[] b, int off, int len) throws IOException {
44 if (channel.position() + len < channel.size()) {
45 FileUtils.readFully(channel, ByteBuffer.wrap(b, off, len));
46 return len;
47 }
48 return super.read(b, off, len);
49 }
50
51 public void close() throws IOException {
52 channel.close();
53 }
54
55 }
56