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 8.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. /*
  2. * Copyright (c) 2006-2010 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.addons.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.nio.charset.Charset;
  29. import java.util.Stack;
  30. import java.util.ArrayList;
  31. /**
  32. * Reads a file in reverse.
  33. *
  34. * @author Shane 'Dataforce' McCormack
  35. */
  36. public class ReverseFileReader {
  37. /** File to manipulate. */
  38. private RandomAccessFile file;
  39. /** Number of bytes to skip backwards at a time. */
  40. private byte seekLength = 50;
  41. /**
  42. * Create a new ReverseFileReader.
  43. *
  44. * @param filename File to open.
  45. * @throws FileNotFoundException If the file is not a regular file.
  46. * @throws SecurityException If a security manager exists and its checkRead method denies read access to the file.
  47. * @throws IOException If there is an error seeking to the end of the file.
  48. */
  49. public ReverseFileReader(String filename) throws FileNotFoundException, SecurityException, IOException {
  50. file = new RandomAccessFile(filename, "r");
  51. reset();
  52. }
  53. /**
  54. * Create a new ReverseFileReader.
  55. *
  56. * @param myFile Existing file to use.
  57. * @throws FileNotFoundException If the file is not a regular file.
  58. * @throws SecurityException If a security manager exists and its checkRead method denies read access to the file.
  59. * @throws IOException If there is an error seeking to the end of the file.
  60. */
  61. public ReverseFileReader(File myFile) throws FileNotFoundException, SecurityException, IOException {
  62. file = new RandomAccessFile(myFile, "r");
  63. reset();
  64. }
  65. /**
  66. * Reset the file pointer to the end of the file.
  67. *
  68. * @throws IOException If there is an error seeking, or the file is closed.
  69. */
  70. public void reset() throws IOException {
  71. if (file == null) {
  72. throw new IOException("File has been closed.");
  73. }
  74. file.seek(file.length());
  75. }
  76. /**
  77. * Get the current seekLength.
  78. *
  79. * @return current seekLength
  80. */
  81. public byte getSeekLength() {
  82. return seekLength;
  83. }
  84. /**
  85. * Set the seekLength.
  86. *
  87. * @param newValue New value for seekLength
  88. */
  89. public void setSeekLength(final byte newValue) {
  90. seekLength = newValue;
  91. }
  92. /**
  93. * Close the file pointer.
  94. * This should be called before removing the reference to this object
  95. *
  96. * @throws IOException If there is an error closing the file, or if it has been closed already.
  97. */
  98. public void close() throws IOException {
  99. if (file == null) {
  100. throw new IOException("File has been closed.");
  101. }
  102. file.close();
  103. file = null;
  104. }
  105. /**
  106. * Get the next full line.
  107. *
  108. * @return The next full line.
  109. * @throws EOFException If there is no more lines.
  110. * @throws IOException If an error reading or seeking occured, or if the fiel is closed.
  111. */
  112. public String getNextLine() throws EOFException, IOException {
  113. if (file == null) {
  114. throw new IOException("File has been closed.");
  115. }
  116. // Used to store result to output.
  117. // StringBuilder line = new StringBuilder();
  118. final ArrayList<Byte> line = new ArrayList<Byte>(seekLength);
  119. // Used to store position in file pre-read
  120. long fp = 0;
  121. // Used to store position in file when this is called
  122. long startfp = 0;
  123. // Used to store read bytes
  124. byte[] bytes;
  125. // Distance seeked
  126. int seekDistance = 0;
  127. // Check current position, if 0 we are at the start of the file
  128. // and should throw an exception.
  129. startfp = file.getFilePointer();
  130. if (startfp == 0) {
  131. throw new EOFException("Reached Start of file");
  132. }
  133. // Keep looping untill we get a full line, or the end of the file
  134. boolean keepLooping = true;
  135. boolean gotNewLine;
  136. while (keepLooping) {
  137. gotNewLine = false;
  138. // Get Current Position
  139. fp = file.getFilePointer();
  140. // Check how far to seek backwards (seekLength or to the start of the file)
  141. if (fp < seekLength) {
  142. // Seek to the start of the file;
  143. seekDistance = (int) fp;
  144. fp = 0;
  145. } else {
  146. // Seek to position current-seekLength
  147. seekDistance = seekLength;
  148. fp = fp - seekDistance;
  149. }
  150. // Seek!
  151. file.seek(fp);
  152. bytes = new byte[seekDistance];
  153. // Read into the bytes array
  154. file.read(bytes);
  155. // And loop looking for data
  156. // This uses seekDistance so that only wanted data is checked.
  157. for (int i = seekDistance - 1; i >= 0; --i) {
  158. // Check for New line Character, or a non carraige-return char
  159. if (bytes[i] == '\n') {
  160. // Seek to the location of this character and exit this loop.
  161. file.seek(fp + i);
  162. gotNewLine = true;
  163. break;
  164. } else if (bytes[i] != '\r') {
  165. // Add to the result, the loop will continue going.
  166. line.add(0, bytes[i]);
  167. }
  168. }
  169. // We have now processed the data we read (Either added it all to the
  170. // buffer, or found a newline character.)
  171. if (fp == 0 && !gotNewLine) {
  172. // This part of the loop started from the start of the file, but didn't
  173. // find a new line anywhere. no more loops are posssible, so Treat
  174. // this as "got new line"
  175. gotNewLine = true;
  176. file.seek(0);
  177. }
  178. // Do we need to continue?
  179. if (gotNewLine) {
  180. // We have found a new line somewhere, thus we don't need
  181. // to read any more bytes, so exit the while loop!
  182. keepLooping = false;
  183. } else {
  184. // We have not found a new line anywhere,
  185. // Seek to the pre-read position, and repeat.
  186. file.seek(fp);
  187. }
  188. }
  189. // Return the data obtained.
  190. byte[] result = new byte[line.size()];
  191. for (int i = 0; i < line.size(); ++i) {
  192. result[i] = line.get(i);
  193. }
  194. return new String(result, Charset.forName("UTF-8"));
  195. }
  196. /**
  197. * Try and get x number of lines.
  198. * If the file is closed, an empty stack will be returned.
  199. *
  200. * @param numLines Number of lines to try and get.
  201. * @return The requested lines
  202. */
  203. public Stack<String> getLines(final int numLines) {
  204. final Stack<String> result = new Stack<String>();
  205. for (int i = 0; i < numLines; ++i) {
  206. try {
  207. result.push(getNextLine());
  208. } catch (IOException e) {
  209. break;
  210. }
  211. }
  212. return result;
  213. }
  214. /**
  215. * Try and get x number of lines and return a \n delimited String.
  216. * If the file is closed, an empty string will be returned.
  217. *
  218. * @param numLines Number of lines to try and get.
  219. * @return The requested lines
  220. */
  221. public String getLinesAsString(final int numLines) {
  222. final StringBuilder result = new StringBuilder();
  223. for (int i = 0; i < numLines; ++i) {
  224. try {
  225. result.insert(0, "\n");
  226. result.insert(0, getNextLine());
  227. } catch (IOException e) {
  228. break;
  229. }
  230. }
  231. if (result.charAt(0) == '\n') {
  232. result.deleteCharAt(0);
  233. }
  234. return result.toString();
  235. }
  236. }