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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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 org.eclipse.jgit.internal.JGitText;
  56. /**
  57. * Input/Output utilities
  58. */
  59. public class IO {
  60. /**
  61. * Read an entire local file into memory as a byte array.
  62. *
  63. * @param path
  64. * location of the file to read.
  65. * @return complete contents of the requested local file.
  66. * @throws FileNotFoundException
  67. * the file does not exist.
  68. * @throws IOException
  69. * the file exists, but its contents cannot be read.
  70. */
  71. public static final byte[] readFully(final File path)
  72. throws FileNotFoundException, IOException {
  73. return IO.readFully(path, Integer.MAX_VALUE);
  74. }
  75. /**
  76. * Read at most limit bytes from the local file into memory as a byte array.
  77. *
  78. * @param path
  79. * location of the file to read.
  80. * @param limit
  81. * maximum number of bytes to read, if the file is larger than
  82. * only the first limit number of bytes are returned
  83. * @return complete contents of the requested local file. If the contents
  84. * exceeds the limit, then only the limit is returned.
  85. * @throws FileNotFoundException
  86. * the file does not exist.
  87. * @throws IOException
  88. * the file exists, but its contents cannot be read.
  89. */
  90. public static final byte[] readSome(final File path, final int limit)
  91. throws FileNotFoundException, IOException {
  92. FileInputStream in = new FileInputStream(path);
  93. try {
  94. byte[] buf = new byte[limit];
  95. int cnt = 0;
  96. for (;;) {
  97. int n = in.read(buf, cnt, buf.length - cnt);
  98. if (n <= 0)
  99. break;
  100. cnt += n;
  101. }
  102. if (cnt == buf.length)
  103. return buf;
  104. byte[] res = new byte[cnt];
  105. System.arraycopy(buf, 0, res, 0, cnt);
  106. return res;
  107. } finally {
  108. try {
  109. in.close();
  110. } catch (IOException ignored) {
  111. // do nothing
  112. }
  113. }
  114. }
  115. /**
  116. * Read an entire local file into memory as a byte array.
  117. *
  118. * @param path
  119. * location of the file to read.
  120. * @param max
  121. * maximum number of bytes to read, if the file is larger than
  122. * this limit an IOException is thrown.
  123. * @return complete contents of the requested local file.
  124. * @throws FileNotFoundException
  125. * the file does not exist.
  126. * @throws IOException
  127. * the file exists, but its contents cannot be read.
  128. */
  129. public static final byte[] readFully(final File path, final int max)
  130. throws FileNotFoundException, IOException {
  131. final FileInputStream in = new FileInputStream(path);
  132. try {
  133. long sz = Math.max(path.length(), 1);
  134. if (sz > max)
  135. throw new IOException(MessageFormat.format(
  136. JGitText.get().fileIsTooLarge, path));
  137. byte[] buf = new byte[(int) sz];
  138. int valid = 0;
  139. for (;;) {
  140. if (buf.length == valid) {
  141. if (buf.length == max) {
  142. int next = in.read();
  143. if (next < 0)
  144. break;
  145. throw new IOException(MessageFormat.format(
  146. JGitText.get().fileIsTooLarge, path));
  147. }
  148. byte[] nb = new byte[Math.min(buf.length * 2, max)];
  149. System.arraycopy(buf, 0, nb, 0, valid);
  150. buf = nb;
  151. }
  152. int n = in.read(buf, valid, buf.length - valid);
  153. if (n < 0)
  154. break;
  155. valid += n;
  156. }
  157. if (valid < buf.length) {
  158. byte[] nb = new byte[valid];
  159. System.arraycopy(buf, 0, nb, 0, valid);
  160. buf = nb;
  161. }
  162. return buf;
  163. } finally {
  164. try {
  165. in.close();
  166. } catch (IOException ignored) {
  167. // ignore any close errors, this was a read only stream
  168. }
  169. }
  170. }
  171. /**
  172. * Read an entire input stream into memory as a ByteBuffer.
  173. *
  174. * Note: The stream is read to its end and is not usable after calling this
  175. * method. The caller is responsible for closing the stream.
  176. *
  177. * @param in
  178. * input stream to be read.
  179. * @param sizeHint
  180. * a hint on the approximate number of bytes contained in the
  181. * stream, used to allocate temporary buffers more efficiently
  182. * @return complete contents of the input stream. The ByteBuffer always has
  183. * a writable backing array, with {@code position() == 0} and
  184. * {@code limit()} equal to the actual length read. Callers may rely
  185. * on obtaining the underlying array for efficient data access. If
  186. * {@code sizeHint} was too large, the array may be over-allocated,
  187. * resulting in {@code limit() < array().length}.
  188. * @throws IOException
  189. * there was an error reading from the stream.
  190. */
  191. public static ByteBuffer readWholeStream(InputStream in, int sizeHint)
  192. throws IOException {
  193. byte[] out = new byte[sizeHint];
  194. int pos = 0;
  195. while (pos < out.length) {
  196. int read = in.read(out, pos, out.length - pos);
  197. if (read < 0)
  198. return ByteBuffer.wrap(out, 0, pos);
  199. pos += read;
  200. }
  201. int last = in.read();
  202. if (last < 0)
  203. return ByteBuffer.wrap(out, 0, pos);
  204. TemporaryBuffer.Heap tmp = new TemporaryBuffer.Heap(Integer.MAX_VALUE);
  205. tmp.write(out);
  206. tmp.write(last);
  207. tmp.copy(in);
  208. return ByteBuffer.wrap(tmp.toByteArray());
  209. }
  210. /**
  211. * Read the entire byte array into memory, or throw an exception.
  212. *
  213. * @param fd
  214. * input stream to read the data from.
  215. * @param dst
  216. * buffer that must be fully populated, [off, off+len).
  217. * @param off
  218. * position within the buffer to start writing to.
  219. * @param len
  220. * number of bytes that must be read.
  221. * @throws EOFException
  222. * the stream ended before dst was fully populated.
  223. * @throws IOException
  224. * there was an error reading from the stream.
  225. */
  226. public static void readFully(final InputStream fd, final byte[] dst,
  227. int off, int len) throws IOException {
  228. while (len > 0) {
  229. final int r = fd.read(dst, off, len);
  230. if (r <= 0)
  231. throw new EOFException(JGitText.get().shortReadOfBlock);
  232. off += r;
  233. len -= r;
  234. }
  235. }
  236. /**
  237. * Read as much of the array as possible from a channel.
  238. *
  239. * @param channel
  240. * channel to read data from.
  241. * @param dst
  242. * buffer that must be fully populated, [off, off+len).
  243. * @param off
  244. * position within the buffer to start writing to.
  245. * @param len
  246. * number of bytes that should be read.
  247. * @return number of bytes actually read.
  248. * @throws IOException
  249. * there was an error reading from the channel.
  250. */
  251. public static int read(ReadableByteChannel channel, byte[] dst, int off,
  252. int len) throws IOException {
  253. if (len == 0)
  254. return 0;
  255. int cnt = 0;
  256. while (0 < len) {
  257. int r = channel.read(ByteBuffer.wrap(dst, off, len));
  258. if (r <= 0)
  259. break;
  260. off += r;
  261. len -= r;
  262. cnt += r;
  263. }
  264. return cnt != 0 ? cnt : -1;
  265. }
  266. /**
  267. * Read the entire byte array into memory, unless input is shorter
  268. *
  269. * @param fd
  270. * input stream to read the data from.
  271. * @param dst
  272. * buffer that must be fully populated, [off, off+len).
  273. * @param off
  274. * position within the buffer to start writing to.
  275. * @return number of bytes in buffer or stream, whichever is shortest
  276. * @throws IOException
  277. * there was an error reading from the stream.
  278. */
  279. public static int readFully(InputStream fd, byte[] dst, int off)
  280. throws IOException {
  281. int r;
  282. int len = 0;
  283. while ((r = fd.read(dst, off, dst.length - off)) >= 0
  284. && len < dst.length) {
  285. off += r;
  286. len += r;
  287. }
  288. return len;
  289. }
  290. /**
  291. * Skip an entire region of an input stream.
  292. * <p>
  293. * The input stream's position is moved forward by the number of requested
  294. * bytes, discarding them from the input. This method does not return until
  295. * the exact number of bytes requested has been skipped.
  296. *
  297. * @param fd
  298. * the stream to skip bytes from.
  299. * @param toSkip
  300. * total number of bytes to be discarded. Must be >= 0.
  301. * @throws EOFException
  302. * the stream ended before the requested number of bytes were
  303. * skipped.
  304. * @throws IOException
  305. * there was an error reading from the stream.
  306. */
  307. public static void skipFully(final InputStream fd, long toSkip)
  308. throws IOException {
  309. while (toSkip > 0) {
  310. final long r = fd.skip(toSkip);
  311. if (r <= 0)
  312. throw new EOFException(JGitText.get().shortSkipOfBlock);
  313. toSkip -= r;
  314. }
  315. }
  316. private IO() {
  317. // Don't create instances of a static only utility.
  318. }
  319. }