You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ReverseFileReader.java 7.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. /*
  2. * Copyright (c) 2006-2007 Chris Smith, Shane Mc Cormack, Gregory Holmes
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. * SOFTWARE.
  21. */
  22. package com.dmdirc.plugins.plugins.logging;
  23. import java.io.File;
  24. import java.io.FileNotFoundException;
  25. import java.io.RandomAccessFile;
  26. import java.io.IOException;
  27. import java.io.EOFException;
  28. import java.util.Stack;
  29. /**
  30. * Reads a file in reverse.
  31. *
  32. * @author Shane 'Dataforce' McCormack
  33. * @version $Id: ReverseFileReader.java 969 2007-04-30 18:38:20Z ShaneMcC $
  34. */
  35. public class ReverseFileReader {
  36. /** File to manipulate. */
  37. private RandomAccessFile file;
  38. /** \r Character */
  39. private static final byte r = 0X0D;
  40. /** \n Character */
  41. private static final byte n = 0X0A;
  42. /** Number of bytes to skip backwards at a time. */
  43. private byte seekLength = 50;
  44. /**
  45. * Create a new ReverseFileReader.
  46. *
  47. * @param filename File to open.
  48. * @throws FileNotFoundException If the file is not a regular file.
  49. * @throws SecurityException If a security manager exists and its checkRead method denies read access to the file.
  50. * @throws IOException If there is an error seeking to the end of the file.
  51. */
  52. public ReverseFileReader(String filename) throws FileNotFoundException, SecurityException, IOException {
  53. file = new RandomAccessFile(filename, "r");
  54. reset();
  55. }
  56. /**
  57. * Create a new ReverseFileReader.
  58. *
  59. * @param myFile Existing file to use.
  60. * @throws FileNotFoundException If the file is not a regular file.
  61. * @throws SecurityException If a security manager exists and its checkRead method denies read access to the file.
  62. * @throws IOException If there is an error seeking to the end of the file.
  63. */
  64. public ReverseFileReader(File myFile) throws FileNotFoundException, SecurityException, IOException {
  65. file = new RandomAccessFile(myFile, "r");
  66. reset();
  67. }
  68. /**
  69. * Reset the file pointer to the end of the file.
  70. *
  71. * @throws IOException If there is an error seeking, or the file is closed.
  72. */
  73. public void reset() throws IOException {
  74. if (file == null) { throw new IOException("File has been closed."); }
  75. file.seek(file.length());
  76. }
  77. /**
  78. * Get the current seekLength.
  79. *
  80. * @return current seekLength
  81. */
  82. public byte getSeekLength() {
  83. return seekLength;
  84. }
  85. /**
  86. * Set the seekLength.
  87. *
  88. * @param newValue New value for seekLength
  89. */
  90. public void setSeekLength(byte newValue) {
  91. seekLength = newValue;
  92. }
  93. /**
  94. * Close the file pointer.
  95. * This should be called before removing the reference to this object
  96. *
  97. * @throws IOException If there is an error closing the file, or if it has been closed already.
  98. */
  99. public void close() throws IOException {
  100. if (file == null) { throw new IOException("File has been closed."); }
  101. file.close();
  102. file = null;
  103. }
  104. /**
  105. * Get the next full line.
  106. *
  107. * @return The next full line.
  108. * @throws EOFException If there is no more lines.
  109. * @throws IOException If an error reading or seeking occured, or if the fiel is closed.
  110. */
  111. public String getNextLine() throws EOFException, IOException {
  112. if (file == null) { throw new IOException("File has been closed."); }
  113. // Used to store result to output.
  114. StringBuilder line = new StringBuilder();
  115. // Used to store position in file pre-read
  116. long fp = 0;
  117. // Used to store position in file when this is called
  118. long startfp = 0;
  119. // Used to store read bytes
  120. byte[] bytes = new byte[seekLength];
  121. // Distance seeked
  122. int seekDistance = 0;
  123. // Check current position, if 0 we are at the start of the file
  124. // and should throw an exception.
  125. startfp = file.getFilePointer();
  126. if (startfp == 0) {
  127. throw new EOFException("Reached Start of file");
  128. }
  129. // Keep looping untill we get a full line, or the end of the file
  130. while (true) {
  131. // Get Current Position
  132. fp = file.getFilePointer();
  133. // Check how far to seek backwards (seekLength or to the start of the file)
  134. if (fp < seekLength) {
  135. // Seek to the start of the file;
  136. seekDistance = (int)fp;
  137. fp = 0;
  138. } else {
  139. // Seek to position current-seekLength
  140. seekDistance = seekLength;
  141. fp = fp - seekDistance;
  142. }
  143. // Seek!
  144. file.seek(fp);
  145. // Read into the bytes array (This will read seekLength bytes)
  146. file.read(bytes);
  147. // And loop looking for data
  148. // This uses seekDistance so that only wanted data is checked.
  149. for (int i = seekDistance-1; i >= 0; --i) {
  150. // Check for New line Character, or a non carraige-return char
  151. if (bytes[i] == n) {
  152. // Seek to the location of this character and exit this loop.
  153. file.seek(fp+i);
  154. break;
  155. } else if (bytes[i] != r) {
  156. // Add to the result, the loop will continue going.
  157. line.append((char)bytes[i]);
  158. }
  159. }
  160. // We have now processed the data we read (Either added it all to the
  161. // buffer, or found a newline character.
  162. // "fp" is where we started reading from, "file.getFilePointer()"
  163. // is where we are at now. If they are not the same then we found
  164. // a new line somewhere, else we read all "seekDistance" bytes and
  165. // need to read another amount of bytes.
  166. if (fp != (file.getFilePointer()-seekDistance)) {
  167. // We have found a new line somewhere, thus we don't need
  168. // to read any more bytes, so exit the while loop!
  169. break;
  170. } else {
  171. // We have not found a new line anywhere,
  172. // Seek to the pre-read position, and repeat.
  173. file.seek(fp);
  174. }
  175. }
  176. // If the current position is past the position we started at, then
  177. // set the file position back to 0, this will cause the next attempt
  178. // tp read a line to throw an EOFException.
  179. if (startfp < file.getFilePointer()) {
  180. file.seek(0);
  181. }
  182. // Return the data obtained. (we reverse the string buffer because we
  183. // add to it in reverse, so this fixes it to go in the correct order)
  184. return line.reverse().toString();
  185. }
  186. /**
  187. * Try and get x number of lines.
  188. * If the file is closed, an empty stack will be returned.
  189. *
  190. * @param numLines Number of lines to try and get.
  191. */
  192. public Stack<String> getLines(int numLines) {
  193. Stack<String> result = new Stack<String>();
  194. for (int i = 0; i < numLines; ++i) {
  195. try {
  196. result.push(getNextLine());
  197. } catch (IOException e) {
  198. break;
  199. }
  200. }
  201. return result;
  202. }
  203. }