Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

ReverseFileReader.java 8.3KB

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