View Javadoc
1   /*
2    * Licensed under the GPL License. You may not use this file except in compliance with the License.
3    * You may obtain a copy of the License at
4    *
5    *   https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
6    *
7    * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
8    * WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
9    * PURPOSE.
10   */
11  package psiprobe.tools;
12  
13  import java.io.File;
14  import java.io.IOException;
15  import java.io.InputStream;
16  import java.io.RandomAccessFile;
17  
18  /**
19   * The Class BackwardsFileStream.
20   */
21  public class BackwardsFileStream extends InputStream {
22  
23    /** The raf. */
24    private final RandomAccessFile raf;
25  
26    /** The seek pos. */
27    private long seekPos;
28  
29    /**
30     * Instantiates a new backwards file stream.
31     *
32     * @param file the file
33     *
34     * @throws IOException Signals that an I/O exception has occurred.
35     */
36    public BackwardsFileStream(File file) throws IOException {
37      raf = new RandomAccessFile(file, "r");
38      seekPos = raf.length();
39    }
40  
41    /**
42     * Instantiates a new backwards file stream.
43     *
44     * @param file the file
45     * @param pos the pos
46     *
47     * @throws IOException Signals that an I/O exception has occurred.
48     */
49    public BackwardsFileStream(File file, long pos) throws IOException {
50      raf = new RandomAccessFile(file, "r");
51      seekPos = pos;
52    }
53  
54    @Override
55    public int read() throws IOException {
56      if (seekPos > 0) {
57        raf.seek(--seekPos);
58        return raf.read();
59      }
60      // return EOF (so to speak)
61      return -1;
62    }
63  
64    @Override
65    public void close() throws IOException {
66      if (raf != null) {
67        raf.close();
68      }
69    }
70  
71  }