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.

IO.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. /*
  2. * Copyright (C) 2008-2009, Google Inc.
  3. * Copyright (C) 2009, Robin Rosenberg <robin.rosenberg@dewire.com>
  4. * Copyright (C) 2006-2008, Shawn O. Pearce <spearce@spearce.org>
  5. * and other copyright owners as documented in the project's IP log.
  6. *
  7. * This program and the accompanying materials are made available
  8. * under the terms of the Eclipse Distribution License v1.0 which
  9. * accompanies this distribution, is reproduced below, and is
  10. * available at http://www.eclipse.org/org/documents/edl-v10.php
  11. *
  12. * All rights reserved.
  13. *
  14. * Redistribution and use in source and binary forms, with or
  15. * without modification, are permitted provided that the following
  16. * conditions are met:
  17. *
  18. * - Redistributions of source code must retain the above copyright
  19. * notice, this list of conditions and the following disclaimer.
  20. *
  21. * - Redistributions in binary form must reproduce the above
  22. * copyright notice, this list of conditions and the following
  23. * disclaimer in the documentation and/or other materials provided
  24. * with the distribution.
  25. *
  26. * - Neither the name of the Eclipse Foundation, Inc. nor the
  27. * names of its contributors may be used to endorse or promote
  28. * products derived from this software without specific prior
  29. * written permission.
  30. *
  31. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  32. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  33. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  34. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  35. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  36. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  37. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  38. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  39. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  40. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  41. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  42. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  43. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  44. */
  45. package org.eclipse.jgit.util;
  46. import java.io.EOFException;
  47. import java.io.File;
  48. import java.io.FileInputStream;
  49. import java.io.FileNotFoundException;
  50. import java.io.IOException;
  51. import java.io.InputStream;
  52. import java.nio.ByteBuffer;
  53. import java.nio.channels.ReadableByteChannel;
  54. import java.text.MessageFormat;
  55. import java.util.ArrayList;
  56. import java.util.List;
  57. import org.eclipse.jgit.internal.JGitText;
  58. /**
  59. * Input/Output utilities
  60. */
  61. public class IO {
  62. /**
  63. * Read an entire local file into memory as a byte array.
  64. *
  65. * @param path
  66. * location of the file to read.
  67. * @return complete contents of the requested local file.
  68. * @throws FileNotFoundException
  69. * the file does not exist.
  70. * @throws IOException
  71. * the file exists, but its contents cannot be read.
  72. */
  73. public static final byte[] readFully(final File path)
  74. throws FileNotFoundException, IOException {
  75. return IO.readFully(path, Integer.MAX_VALUE);
  76. }
  77. /**
  78. * Read at most limit bytes from the local file into memory as a byte array.
  79. *
  80. * @param path
  81. * location of the file to read.
  82. * @param limit
  83. * maximum number of bytes to read, if the file is larger than
  84. * only the first limit number of bytes are returned
  85. * @return complete contents of the requested local file. If the contents
  86. * exceeds the limit, then only the limit is returned.
  87. * @throws FileNotFoundException
  88. * the file does not exist.
  89. * @throws IOException
  90. * the file exists, but its contents cannot be read.
  91. */
  92. public static final byte[] readSome(final File path, final int limit)
  93. throws FileNotFoundException, IOException {
  94. FileInputStream in = new FileInputStream(path);
  95. try {
  96. byte[] buf = new byte[limit];
  97. int cnt = 0;
  98. for (;;) {
  99. int n = in.read(buf, cnt, buf.length - cnt);
  100. if (n <= 0)
  101. break;
  102. cnt += n;
  103. }
  104. if (cnt == buf.length)
  105. return buf;
  106. byte[] res = new byte[cnt];
  107. System.arraycopy(buf, 0, res, 0, cnt);
  108. return res;
  109. } finally {
  110. try {
  111. in.close();
  112. } catch (IOException ignored) {
  113. // do nothing
  114. }
  115. }
  116. }
  117. /**
  118. * Read an entire local file into memory as a byte array.
  119. *
  120. * @param path
  121. * location of the file to read.
  122. * @param max
  123. * maximum number of bytes to read, if the file is larger than
  124. * this limit an IOException is thrown.
  125. * @return complete contents of the requested local file.
  126. * @throws FileNotFoundException
  127. * the file does not exist.
  128. * @throws IOException
  129. * the file exists, but its contents cannot be read.
  130. */
  131. public static final byte[] readFully(final File path, final int max)
  132. throws FileNotFoundException, IOException {
  133. final FileInputStream in = new FileInputStream(path);
  134. try {
  135. final long sz = in.getChannel().size();
  136. if (sz > max)
  137. throw new IOException(MessageFormat.format(
  138. JGitText.get().fileIsTooLarge, path));
  139. final byte[] buf = new byte[(int) sz];
  140. IO.readFully(in, buf, 0);
  141. return buf;
  142. } finally {
  143. try {
  144. in.close();
  145. } catch (IOException ignored) {
  146. // ignore any close errors, this was a read only stream
  147. }
  148. }
  149. }
  150. /**
  151. * Read an entire input stream into memory as a ByteBuffer.
  152. *
  153. * Note: The stream is read to its end and is not usable after calling this
  154. * method. The caller is responsible for closing the stream.
  155. *
  156. * @param in
  157. * input stream to be read.
  158. * @param sizeHint
  159. * a hint on the approximate number of bytes contained in the
  160. * stream, used to allocate temporary buffers more efficiently
  161. * @return complete contents of the input stream. The ByteBuffer always has
  162. * a writable backing array, with {@code position() == 0} and
  163. * {@code limit()} equal to the actual length read. Callers may rely
  164. * on obtaining the underlying array for efficient data access. If
  165. * {@code sizeHint} was too large, the array may be over-allocated,
  166. * resulting in {@code limit() < array().length}.
  167. * @throws IOException
  168. * there was an error reading from the stream.
  169. */
  170. public static ByteBuffer readWholeStream(InputStream in, int sizeHint)
  171. throws IOException {
  172. byte[] out = new byte[sizeHint];
  173. int pos = 0;
  174. while (pos < out.length) {
  175. int read = in.read(out, pos, out.length - pos);
  176. if (read < 0)
  177. return ByteBuffer.wrap(out, 0, pos);
  178. pos += read;
  179. }
  180. int last = in.read();
  181. if (last < 0)
  182. return ByteBuffer.wrap(out, 0, pos);
  183. TemporaryBuffer.Heap tmp = new TemporaryBuffer.Heap(Integer.MAX_VALUE);
  184. tmp.write(out);
  185. tmp.write(last);
  186. tmp.copy(in);
  187. return ByteBuffer.wrap(tmp.toByteArray());
  188. }
  189. /**
  190. * Read the entire byte array into memory, or throw an exception.
  191. *
  192. * @param fd
  193. * input stream to read the data from.
  194. * @param dst
  195. * buffer that must be fully populated, [off, off+len).
  196. * @param off
  197. * position within the buffer to start writing to.
  198. * @param len
  199. * number of bytes that must be read.
  200. * @throws EOFException
  201. * the stream ended before dst was fully populated.
  202. * @throws IOException
  203. * there was an error reading from the stream.
  204. */
  205. public static void readFully(final InputStream fd, final byte[] dst,
  206. int off, int len) throws IOException {
  207. while (len > 0) {
  208. final int r = fd.read(dst, off, len);
  209. if (r <= 0)
  210. throw new EOFException(JGitText.get().shortReadOfBlock);
  211. off += r;
  212. len -= r;
  213. }
  214. }
  215. /**
  216. * Read as much of the array as possible from a channel.
  217. *
  218. * @param channel
  219. * channel to read data from.
  220. * @param dst
  221. * buffer that must be fully populated, [off, off+len).
  222. * @param off
  223. * position within the buffer to start writing to.
  224. * @param len
  225. * number of bytes that should be read.
  226. * @return number of bytes actually read.
  227. * @throws IOException
  228. * there was an error reading from the channel.
  229. */
  230. public static int read(ReadableByteChannel channel, byte[] dst, int off,
  231. int len) throws IOException {
  232. if (len == 0)
  233. return 0;
  234. int cnt = 0;
  235. while (0 < len) {
  236. int r = channel.read(ByteBuffer.wrap(dst, off, len));
  237. if (r <= 0)
  238. break;
  239. off += r;
  240. len -= r;
  241. cnt += r;
  242. }
  243. return cnt != 0 ? cnt : -1;
  244. }
  245. /**
  246. * Read the entire byte array into memory, unless input is shorter
  247. *
  248. * @param fd
  249. * input stream to read the data from.
  250. * @param dst
  251. * buffer that must be fully populated, [off, off+len).
  252. * @param off
  253. * position within the buffer to start writing to.
  254. * @return number of bytes in buffer or stream, whichever is shortest
  255. * @throws IOException
  256. * there was an error reading from the stream.
  257. */
  258. public static int readFully(InputStream fd, byte[] dst, int off)
  259. throws IOException {
  260. int r;
  261. int len = 0;
  262. while ((r = fd.read(dst, off, dst.length - off)) >= 0
  263. && len < dst.length) {
  264. off += r;
  265. len += r;
  266. }
  267. return len;
  268. }
  269. /**
  270. * Skip an entire region of an input stream.
  271. * <p>
  272. * The input stream's position is moved forward by the number of requested
  273. * bytes, discarding them from the input. This method does not return until
  274. * the exact number of bytes requested has been skipped.
  275. *
  276. * @param fd
  277. * the stream to skip bytes from.
  278. * @param toSkip
  279. * total number of bytes to be discarded. Must be >= 0.
  280. * @throws EOFException
  281. * the stream ended before the requested number of bytes were
  282. * skipped.
  283. * @throws IOException
  284. * there was an error reading from the stream.
  285. */
  286. public static void skipFully(final InputStream fd, long toSkip)
  287. throws IOException {
  288. while (toSkip > 0) {
  289. final long r = fd.skip(toSkip);
  290. if (r <= 0)
  291. throw new EOFException(JGitText.get().shortSkipOfBlock);
  292. toSkip -= r;
  293. }
  294. }
  295. /**
  296. * Divides the given string into lines.
  297. *
  298. * @param s
  299. * the string to read
  300. * @return the string divided into lines
  301. */
  302. public static List<String> readLines(final String s) {
  303. List<String> l = new ArrayList<String>();
  304. StringBuilder sb = new StringBuilder();
  305. for (int i = 0; i < s.length(); i++) {
  306. char c = s.charAt(i);
  307. if (c == '\n') {
  308. l.add(sb.toString());
  309. sb.setLength(0);
  310. continue;
  311. }
  312. if (c == '\r') {
  313. if (i + 1 < s.length()) {
  314. c = s.charAt(++i);
  315. l.add(sb.toString());
  316. sb.setLength(0);
  317. if (c != '\n')
  318. sb.append(c);
  319. continue;
  320. } else { // EOF
  321. l.add(sb.toString());
  322. break;
  323. }
  324. }
  325. sb.append(c);
  326. }
  327. l.add(sb.toString());
  328. return l;
  329. }
  330. private IO() {
  331. // Don't create instances of a static only utility.
  332. }
  333. }