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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. /*
  2. * Copyright (c) 2006-2012 DMDirc Developers
  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.util.io;
  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. public class ReverseFileReader {
  35. /** File to manipulate. */
  36. private RandomAccessFile file;
  37. /** Number of bytes to skip backwards at a time. */
  38. private byte seekLength = 50;
  39. /**
  40. * Create a new ReverseFileReader.
  41. *
  42. * @param filename File to open.
  43. * @throws FileNotFoundException If the file is not a regular file.
  44. * @throws SecurityException If a security manager exists and its checkRead method denies read access to the file.
  45. * @throws IOException If there is an error seeking to the end of the file.
  46. */
  47. public ReverseFileReader(final String filename) throws FileNotFoundException,
  48. SecurityException, IOException {
  49. file = new RandomAccessFile(filename, "r");
  50. reset();
  51. }
  52. /**
  53. * Create a new ReverseFileReader.
  54. *
  55. * @param myFile Existing file to use.
  56. * @throws FileNotFoundException If the file is not a regular file.
  57. * @throws SecurityException If a security manager exists and its checkRead method denies read access to the file.
  58. * @throws IOException If there is an error seeking to the end of the file.
  59. */
  60. public ReverseFileReader(final File myFile) throws FileNotFoundException,
  61. 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. final ArrayList<Byte> line = new ArrayList<Byte>(seekLength);
  118. // Used to store position in file pre-read
  119. long fp = 0;
  120. // Used to store position in file when this is called
  121. long startfp = 0;
  122. // Used to store read bytes
  123. byte[] bytes;
  124. // Distance seeked
  125. int seekDistance = 0;
  126. // Check current position, if 0 we are at the start of the file
  127. // and should throw an exception.
  128. startfp = file.getFilePointer();
  129. if (startfp == 0) {
  130. throw new EOFException("Reached Start of file");
  131. }
  132. // Keep looping untill we get a full line, or the end of the file
  133. boolean keepLooping = true;
  134. boolean gotNewLine;
  135. while (keepLooping) {
  136. gotNewLine = false;
  137. // Get Current Position
  138. fp = file.getFilePointer();
  139. // Check how far to seek backwards (seekLength or to the start of the file)
  140. if (fp < seekLength) {
  141. // Seek to the start of the file;
  142. seekDistance = (int) fp;
  143. fp = 0;
  144. } else {
  145. // Seek to position current-seekLength
  146. seekDistance = seekLength;
  147. fp = fp - seekDistance;
  148. }
  149. // Seek!
  150. file.seek(fp);
  151. bytes = new byte[seekDistance];
  152. // Read into the bytes array
  153. file.read(bytes);
  154. // And loop looking for data
  155. // This uses seekDistance so that only wanted data is checked.
  156. for (int i = seekDistance - 1; i >= 0; --i) {
  157. // Check for New line Character, or a non carraige-return char
  158. if (bytes[i] == '\n') {
  159. // Seek to the location of this character and exit this loop.
  160. file.seek(fp + i);
  161. gotNewLine = true;
  162. break;
  163. } else if (bytes[i] != '\r') {
  164. // Add to the result, the loop will continue going.
  165. line.add(0, bytes[i]);
  166. }
  167. }
  168. // We have now processed the data we read (Either added it all to the
  169. // buffer, or found a newline character.)
  170. if (fp == 0 && !gotNewLine) {
  171. // This part of the loop started from the start of the file, but didn't
  172. // find a new line anywhere. no more loops are posssible, so Treat
  173. // this as "got new line"
  174. gotNewLine = true;
  175. file.seek(0);
  176. }
  177. // Do we need to continue?
  178. if (gotNewLine) {
  179. // We have found a new line somewhere, thus we don't need
  180. // to read any more bytes, so exit the while loop!
  181. keepLooping = false;
  182. } else {
  183. // We have not found a new line anywhere,
  184. // Seek to the pre-read position, and repeat.
  185. file.seek(fp);
  186. }
  187. }
  188. // Return the data obtained.
  189. byte[] result = new byte[line.size()];
  190. for (int i = 0; i < line.size(); ++i) {
  191. result[i] = line.get(i);
  192. }
  193. return new String(result, Charset.forName("UTF-8"));
  194. }
  195. /**
  196. * Try and get x number of lines.
  197. * If the file is closed, an empty stack will be returned.
  198. *
  199. * @param numLines Number of lines to try and get.
  200. * @return The requested lines
  201. */
  202. public Stack<String> getLines(final int numLines) {
  203. final Stack<String> result = new Stack<String>();
  204. for (int i = 0; i < numLines; ++i) {
  205. try {
  206. result.push(getNextLine());
  207. } catch (IOException e) {
  208. break;
  209. }
  210. }
  211. return result;
  212. }
  213. /**
  214. * Try and get x number of lines and return a \n delimited String.
  215. * If the file is closed, an empty string will be returned.
  216. *
  217. * @param numLines Number of lines to try and get.
  218. * @return The requested lines
  219. */
  220. public String getLinesAsString(final int numLines) {
  221. final StringBuilder result = new StringBuilder();
  222. for (int i = 0; i < numLines; ++i) {
  223. try {
  224. result.insert(0, "\n");
  225. result.insert(0, getNextLine());
  226. } catch (IOException e) {
  227. break;
  228. }
  229. }
  230. if (result.charAt(0) == '\n') {
  231. result.deleteCharAt(0);
  232. }
  233. return result.toString();
  234. }
  235. }