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

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