Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

ReverseFileReader.java 8.1KB

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