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.OutputStream; |
10 | import java.nio.ByteBuffer; |
11 | import java.nio.channels.FileChannel; |
12 | |
13 | /** |
14 | * Allows to write to a file channel like an output stream. |
15 | */ |
16 | public class FileChannelOutputStream extends OutputStream { |
17 | |
18 | private final FileChannel channel; |
19 | private final byte[] buffer = { 0 }; |
20 | |
21 | /** |
22 | * Create a new file object output stream from the file channel. |
23 | * |
24 | * @param channel the file channel |
25 | * @param append true for append mode, false for truncate and overwrite |
26 | */ |
27 | public FileChannelOutputStream(FileChannel channel, boolean append) |
28 | 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 | @Override |
39 | public void write(int b) throws IOException { |
40 | buffer[0] = (byte) b; |
41 | FileUtils.writeFully(channel, ByteBuffer.wrap(buffer)); |
42 | } |
43 | |
44 | @Override |
45 | public void write(byte[] b) throws IOException { |
46 | FileUtils.writeFully(channel, ByteBuffer.wrap(b)); |
47 | } |
48 | |
49 | @Override |
50 | public void write(byte[] b, int off, int len) throws IOException { |
51 | FileUtils.writeFully(channel, ByteBuffer.wrap(b, off, len)); |
52 | } |
53 | |
54 | @Override |
55 | public void close() throws IOException { |
56 | channel.close(); |
57 | } |
58 | |
59 | } |