File D:\maven-qcr-plugin-testsunitaires\qcr4java\h2-1.3.170-sources\target\site\qc\lecode\store\fs\FileChannelOutputStream.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.OutputStream;
11 import java.nio.ByteBuffer;
12 import java.nio.channels.FileChannel;
13
14 /**
15 * Allows to write to a file channel like an output stream.
16 */
17 public class FileChannelOutputStream extends OutputStream {
18
19 private final FileChannel channel;
20 private final byte[] buffer = { 0 };
21
22 /**
23 * Create a new file object output stream from the file channel.
24 *
25 * @param channel the file channel
26 * @param append true for append mode, false for truncate and overwrite
27 */
28 public FileChannelOutputStream(FileChannel channel, boolean append) throws IOException {
29 this.channel = channel;
30 if (append) {
31 channel.position(channel.size());
32 } else {
33 channel.position(0);
34 channel.truncate(0);
35 }
36 }
37
38 public void write(int b) throws IOException {
39 buffer[0] = (byte) b;
40 FileUtils.writeFully(channel, ByteBuffer.wrap(buffer));
41 }
42
43 public void write(byte[] b) throws IOException {
44 FileUtils.writeFully(channel, ByteBuffer.wrap(b));
45 }
46
47 public void write(byte[] b, int off, int len) throws IOException {
48 FileUtils.writeFully(channel, ByteBuffer.wrap(b, off, len));
49 }
50
51 public void close() throws IOException {
52 channel.close();
53 }
54
55 }
56