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

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