File D:\maven-qcr-plugin-testsunitaires\qcr4java\h2-1.3.170-sources\target\site\qc\lecode\store\fs\FilePathNio.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.RandomAccessFile;
11 import java.nio.ByteBuffer;
12 import java.nio.channels.FileChannel;
13 import java.nio.channels.FileLock;
14 import java.nio.channels.NonWritableChannelException;
15
16 /**
17 * This file system stores files on disk and uses java.nio to access the files.
18 * This class uses FileChannel.
19 */
20 public class FilePathNio extends FilePathWrapper {
21
22 public FileChannel open(String mode) throws IOException {
23 return new FileNio(name.substring(getScheme().length() + 1), mode);
24 }
25
26 public String getScheme() {
27 return "nio";
28 }
29
30 }
31
32 /**
33 * File which uses NIO FileChannel.
34 */
35 class FileNio extends FileBase {
36
37 private final String name;
38 private final FileChannel channel;
39
40 FileNio(String fileName, String mode) throws IOException {
41 this.name = fileName;
42 channel = new RandomAccessFile(fileName, mode).getChannel();
43 }
44
45 public void implCloseChannel() throws IOException {
46 channel.close();
47 }
48
49 public long position() throws IOException {
50 return channel.position();
51 }
52
53 public long size() throws IOException {
54 return channel.size();
55 }
56
57 public int read(ByteBuffer dst) throws IOException {
58 return channel.read(dst);
59 }
60
61 public FileChannel position(long pos) throws IOException {
62 channel.position(pos);
63 return this;
64 }
65
66 public int read(ByteBuffer dst, long position) throws IOException {
67 return channel.read(dst, position);
68 }
69
70 public int write(ByteBuffer src, long position) throws IOException {
71 return channel.write(src, position);
72 }
73
74 public FileChannel truncate(long newLength) throws IOException {
75 try {
76 channel.truncate(newLength);
77 if (channel.position() > newLength) {
78 // looks like a bug in this FileChannel implementation, as the
79 // documentation says the position needs to be changed
80 channel.position(newLength);
81 }
82 return this;
83 } catch (NonWritableChannelException e) {
84 throw new IOException("read only");
85 }
86 }
87
88 public void force(boolean metaData) throws IOException {
89 channel.force(metaData);
90 }
91
92 public int write(ByteBuffer src) throws IOException {
93 try {
94 return channel.write(src);
95 } catch (NonWritableChannelException e) {
96 throw new IOException("read only");
97 }
98 }
99
100 public synchronized FileLock tryLock(long position, long size, boolean shared) throws IOException {
101 return channel.tryLock(position, size, shared);
102 }
103
104 public String toString() {
105 return "nio:" + name;
106 }
107
108 }
109