Debian Codegraph @

src/uk/me/parabola/imgfmt/sys/FileImgChannel.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2007 Steve Ratcliffe
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2 as
6 * published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 *
14 * Author: Steve Ratcliffe
15 * Create date: Dec 14, 2007
16 */
17 package uk.me.parabola.imgfmt.sys;
18
19 import java.io.FileNotFoundException;
20 import java.io.IOException;
21 import java.io.RandomAccessFile;
22 import java.nio.ByteBuffer;
23 import java.nio.channels.FileChannel;
24
25 import uk.me.parabola.imgfmt.ReadFailedException;
26 import uk.me.parabola.imgfmt.fs.ImgChannel;
27
28 /**
29 * This is an implementation of ImgChannel that delegates to a regular channel.
30 * It can therefore be used to read or write regular files on the file system.
31 *
32 * @author Steve Ratcliffe
33 */
34 public class FileImgChannel implements ImgChannel {
35 private final FileChannel channel;
36 private long position;
37
38 public FileImgChannel(String filename, String mode) {
39 RandomAccessFile raf;
40 try {
41 raf = new RandomAccessFile(filename, mode);
42 } catch (FileNotFoundException e) {
43 throw new ReadFailedException("Could not open " + filename, e);
44 }
45 this.channel = raf.getChannel();
46 }
47
48 public FileImgChannel(FileChannel channel) {
49 this.channel = channel;
50 }
51
52 public int read(ByteBuffer dst) throws IOException {
53 int n = channel.read(dst);
54 if (n > 0)
55 position += n;
56 return n;
57 }
58
59 public boolean isOpen() {
60 return channel.isOpen();
61 }
62
63 public void close() throws IOException {
64 channel.close();
65 }
66
67 public int write(ByteBuffer src) throws IOException {
68 int n = channel.write(src);
69 position += n;
70 return n;
71 }
72
73 /**
74 * Get the file position. Note that this is a logical position relative to the
75 * beginning of the file (the file within the .img file, not the beginning of the
76 * .img file itself).
77 *
78 * @return The offset in bytes from the beginning of the file.
79 */
80 public long position() {
81 return position;
82 }
83
84 /**
85 * Set the position within the file.
86 *
87 * @param pos The position to set.
88 */
89 public void position(long pos) {
90 try {
91 channel.position(pos);
92 position = pos;
93 } catch (IOException e) {
94 throw new ReadFailedException("Could not seek", e);
95 }
96 }
97 }