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.

IOUtils.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.util;
  16. import java.io.ByteArrayOutputStream;
  17. import java.io.Closeable;
  18. import java.io.File;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.io.OutputStream;
  22. import java.io.PushbackInputStream;
  23. import java.nio.ByteBuffer;
  24. import java.nio.channels.ReadableByteChannel;
  25. import java.util.zip.CRC32;
  26. import java.util.zip.Checksum;
  27. import org.apache.poi.EmptyFileException;
  28. import org.apache.poi.POIDocument;
  29. import org.apache.poi.ss.usermodel.Workbook;
  30. public final class IOUtils {
  31. private static final POILogger logger = POILogFactory.getLogger( IOUtils.class );
  32. /**
  33. * The default buffer size to use for the skip() methods.
  34. */
  35. private static final int SKIP_BUFFER_SIZE = 2048;
  36. private static byte[] SKIP_BYTE_BUFFER;
  37. private IOUtils() {
  38. // no instances of this class
  39. }
  40. /**
  41. * Peeks at the first 8 bytes of the stream. Returns those bytes, but
  42. * with the stream unaffected. Requires a stream that supports mark/reset,
  43. * or a PushbackInputStream. If the stream has >0 but <8 bytes,
  44. * remaining bytes will be zero.
  45. * @throws EmptyFileException if the stream is empty
  46. */
  47. public static byte[] peekFirst8Bytes(InputStream stream) throws IOException, EmptyFileException {
  48. return peekFirstNBytes(stream, 8);
  49. }
  50. /**
  51. * Peeks at the first N bytes of the stream. Returns those bytes, but
  52. * with the stream unaffected. Requires a stream that supports mark/reset,
  53. * or a PushbackInputStream. If the stream has >0 but <N bytes,
  54. * remaining bytes will be zero.
  55. * @throws EmptyFileException if the stream is empty
  56. */
  57. public static byte[] peekFirstNBytes(InputStream stream, int limit) throws IOException, EmptyFileException {
  58. stream.mark(limit);
  59. ByteArrayOutputStream bos = new ByteArrayOutputStream(limit);
  60. copy(new BoundedInputStream(stream, limit), bos);
  61. int readBytes = bos.size();
  62. if (readBytes == 0) {
  63. throw new EmptyFileException();
  64. }
  65. if (readBytes < limit) {
  66. bos.write(new byte[limit-readBytes]);
  67. }
  68. byte peekedBytes[] = bos.toByteArray();
  69. if(stream instanceof PushbackInputStream) {
  70. PushbackInputStream pin = (PushbackInputStream)stream;
  71. pin.unread(peekedBytes, 0, readBytes);
  72. } else {
  73. stream.reset();
  74. }
  75. return peekedBytes;
  76. }
  77. /**
  78. * Reads all the data from the input stream, and returns the bytes read.
  79. */
  80. public static byte[] toByteArray(InputStream stream) throws IOException {
  81. return toByteArray(stream, Integer.MAX_VALUE);
  82. }
  83. /**
  84. * Reads up to {@code length} bytes from the input stream, and returns the bytes read.
  85. */
  86. public static byte[] toByteArray(InputStream stream, int length) throws IOException {
  87. ByteArrayOutputStream baos = new ByteArrayOutputStream(length == Integer.MAX_VALUE ? 4096 : length);
  88. byte[] buffer = new byte[4096];
  89. int totalBytes = 0, readBytes;
  90. do {
  91. readBytes = stream.read(buffer, 0, Math.min(buffer.length, length-totalBytes));
  92. totalBytes += Math.max(readBytes,0);
  93. if (readBytes > 0) {
  94. baos.write(buffer, 0, readBytes);
  95. }
  96. } while (totalBytes < length && readBytes > -1);
  97. if (length != Integer.MAX_VALUE && totalBytes < length) {
  98. throw new IOException("unexpected EOF");
  99. }
  100. return baos.toByteArray();
  101. }
  102. /**
  103. * Returns an array (that shouldn't be written to!) of the
  104. * ByteBuffer. Will be of the requested length, or possibly
  105. * longer if that's easier.
  106. */
  107. public static byte[] toByteArray(ByteBuffer buffer, int length) {
  108. if(buffer.hasArray() && buffer.arrayOffset() == 0) {
  109. // The backing array should work out fine for us
  110. return buffer.array();
  111. }
  112. byte[] data = new byte[length];
  113. buffer.get(data);
  114. return data;
  115. }
  116. /**
  117. * Helper method, just calls <tt>readFully(in, b, 0, b.length)</tt>
  118. */
  119. public static int readFully(InputStream in, byte[] b) throws IOException {
  120. return readFully(in, b, 0, b.length);
  121. }
  122. /**
  123. * <p>Same as the normal {@link InputStream#read(byte[], int, int)}, but tries to ensure
  124. * that the entire len number of bytes is read.</p>
  125. *
  126. * <p>If the end of file is reached before any bytes are read, returns <tt>-1</tt>. If
  127. * the end of the file is reached after some bytes are read, returns the
  128. * number of bytes read. If the end of the file isn't reached before <tt>len</tt>
  129. * bytes have been read, will return <tt>len</tt> bytes.</p>
  130. *
  131. * @param in the stream from which the data is read.
  132. * @param b the buffer into which the data is read.
  133. * @param off the start offset in array <tt>b</tt> at which the data is written.
  134. * @param len the maximum number of bytes to read.
  135. */
  136. public static int readFully(InputStream in, byte[] b, int off, int len) throws IOException {
  137. int total = 0;
  138. while (true) {
  139. int got = in.read(b, off + total, len - total);
  140. if (got < 0) {
  141. return (total == 0) ? -1 : total;
  142. }
  143. total += got;
  144. if (total == len) {
  145. return total;
  146. }
  147. }
  148. }
  149. /**
  150. * Same as the normal <tt>channel.read(b)</tt>, but tries to ensure
  151. * that the buffer is filled completely if possible, i.e. b.remaining()
  152. * returns 0.
  153. * <p>
  154. * If the end of file is reached before any bytes are read, returns -1. If
  155. * the end of the file is reached after some bytes are read, returns the
  156. * number of bytes read. If the end of the file isn't reached before the
  157. * buffer has no more remaining capacity, will return the number of bytes
  158. * that were read.
  159. */
  160. public static int readFully(ReadableByteChannel channel, ByteBuffer b) throws IOException {
  161. int total = 0;
  162. while (true) {
  163. int got = channel.read(b);
  164. if (got < 0) {
  165. return (total == 0) ? -1 : total;
  166. }
  167. total += got;
  168. if (total == b.capacity() || b.position() == b.capacity()) {
  169. return total;
  170. }
  171. }
  172. }
  173. /**
  174. * Write a POI Document ({@link org.apache.poi.ss.usermodel.Workbook}, {@link org.apache.poi.sl.usermodel.SlideShow}, etc) to an output stream and close the output stream.
  175. * This will attempt to close the output stream at the end even if there was a problem writing the document to the stream.
  176. *
  177. * If you are using Java 7 or higher, you may prefer to use a try-with-resources statement instead.
  178. * This function exists for Java 6 code.
  179. *
  180. * @param doc a writeable document to write to the output stream
  181. * @param out the output stream that the document is written to
  182. * @throws IOException
  183. */
  184. public static void write(POIDocument doc, OutputStream out) throws IOException {
  185. try {
  186. doc.write(out);
  187. } finally {
  188. closeQuietly(out);
  189. }
  190. }
  191. /**
  192. * Write a ({@link org.apache.poi.ss.usermodel.Workbook}) to an output stream and close the output stream.
  193. * This will attempt to close the output stream at the end even if there was a problem writing the document to the stream.
  194. *
  195. * If you are using Java 7 or higher, you may prefer to use a try-with-resources statement instead.
  196. * This function exists for Java 6 code.
  197. *
  198. * @param doc a writeable document to write to the output stream
  199. * @param out the output stream that the document is written to
  200. * @throws IOException
  201. */
  202. public static void write(Workbook doc, OutputStream out) throws IOException {
  203. try {
  204. doc.write(out);
  205. } finally {
  206. closeQuietly(out);
  207. }
  208. }
  209. /**
  210. * Write a POI Document ({@link org.apache.poi.ss.usermodel.Workbook}, {@link org.apache.poi.sl.usermodel.SlideShow}, etc) to an output stream and close the output stream.
  211. * This will attempt to close the output stream at the end even if there was a problem writing the document to the stream.
  212. * This will also attempt to close the document, even if an error occurred while writing the document or closing the output stream.
  213. *
  214. * If you are using Java 7 or higher, you may prefer to use a try-with-resources statement instead.
  215. * This function exists for Java 6 code.
  216. *
  217. * @param doc a writeable and closeable document to write to the output stream, then close
  218. * @param out the output stream that the document is written to
  219. * @throws IOException
  220. */
  221. public static void writeAndClose(POIDocument doc, OutputStream out) throws IOException {
  222. try {
  223. write(doc, out);
  224. } finally {
  225. closeQuietly(doc);
  226. }
  227. }
  228. /**
  229. * Like {@link #writeAndClose(POIDocument, OutputStream)}, but for writing to a File instead of an OutputStream.
  230. * This will attempt to close the document, even if an error occurred while writing the document.
  231. *
  232. * If you are using Java 7 or higher, you may prefer to use a try-with-resources statement instead.
  233. * This function exists for Java 6 code.
  234. *
  235. * @param doc a writeable and closeable document to write to the output file, then close
  236. * @param out the output file that the document is written to
  237. * @throws IOException
  238. */
  239. public static void writeAndClose(POIDocument doc, File out) throws IOException {
  240. try {
  241. doc.write(out);
  242. } finally {
  243. closeQuietly(doc);
  244. }
  245. }
  246. /**
  247. * Like {@link #writeAndClose(POIDocument, File)}, but for writing a POI Document in place (to the same file that it was opened from).
  248. * This will attempt to close the document, even if an error occurred while writing the document.
  249. *
  250. * If you are using Java 7 or higher, you may prefer to use a try-with-resources statement instead.
  251. * This function exists for Java 6 code.
  252. *
  253. * @param doc a writeable document to write in-place
  254. * @throws IOException
  255. */
  256. public static void writeAndClose(POIDocument doc) throws IOException {
  257. try {
  258. doc.write();
  259. } finally {
  260. closeQuietly(doc);
  261. }
  262. }
  263. // Since the Workbook interface doesn't derive from POIDocument
  264. // We'll likely need one of these for each document container interface
  265. public static void writeAndClose(Workbook doc, OutputStream out) throws IOException {
  266. try {
  267. doc.write(out);
  268. } finally {
  269. closeQuietly(doc);
  270. }
  271. }
  272. /**
  273. * Copies all the data from the given InputStream to the OutputStream. It
  274. * leaves both streams open, so you will still need to close them once done.
  275. */
  276. public static void copy(InputStream inp, OutputStream out) throws IOException {
  277. byte[] buff = new byte[4096];
  278. int count;
  279. while ((count = inp.read(buff)) != -1) {
  280. if (count < -1) {
  281. throw new RecordFormatException("Can't have read < -1 bytes");
  282. }
  283. if (count > 0) {
  284. out.write(buff, 0, count);
  285. }
  286. }
  287. }
  288. /**
  289. * Calculate checksum on input data
  290. */
  291. public static long calculateChecksum(byte[] data) {
  292. Checksum sum = new CRC32();
  293. sum.update(data, 0, data.length);
  294. return sum.getValue();
  295. }
  296. /**
  297. * Calculate checksum on all the data read from input stream.
  298. *
  299. * This should be more efficient than the equivalent code
  300. * {@code IOUtils.calculateChecksum(IOUtils.toByteArray(stream))}
  301. */
  302. public static long calculateChecksum(InputStream stream) throws IOException {
  303. Checksum sum = new CRC32();
  304. byte[] buf = new byte[4096];
  305. int count;
  306. while ((count = stream.read(buf)) != -1) {
  307. if (count > 0) {
  308. sum.update(buf, 0, count);
  309. }
  310. }
  311. return sum.getValue();
  312. }
  313. /**
  314. * Quietly (no exceptions) close Closable resource. In case of error it will
  315. * be printed to {@link IOUtils} class logger.
  316. *
  317. * @param closeable
  318. * resource to close
  319. */
  320. public static void closeQuietly( final Closeable closeable ) {
  321. // no need to log a NullPointerException here
  322. if(closeable == null) {
  323. return;
  324. }
  325. try {
  326. closeable.close();
  327. } catch ( Exception exc ) {
  328. logger.log( POILogger.ERROR, "Unable to close resource: " + exc,
  329. exc );
  330. }
  331. }
  332. /**
  333. * Skips bytes from an input byte stream.
  334. * This implementation guarantees that it will read as many bytes
  335. * as possible before giving up; this may not always be the case for
  336. * skip() implementations in subclasses of {@link InputStream}.
  337. * <p>
  338. * Note that the implementation uses {@link InputStream#read(byte[], int, int)} rather
  339. * than delegating to {@link InputStream#skip(long)}.
  340. * This means that the method may be considerably less efficient than using the actual skip implementation,
  341. * this is done to guarantee that the correct number of bytes are skipped.
  342. * </p>
  343. * <p>
  344. * This mimics POI's {@link #readFully(InputStream, byte[])}.
  345. * If the end of file is reached before any bytes are read, returns <tt>-1</tt>. If
  346. * the end of the file is reached after some bytes are read, returns the
  347. * number of bytes read. If the end of the file isn't reached before <tt>len</tt>
  348. * bytes have been read, will return <tt>len</tt> bytes.</p>
  349. * </p>
  350. * <p>
  351. * Copied nearly verbatim from commons-io 41a3e9c
  352. * </p>
  353. *
  354. * @param input byte stream to skip
  355. * @param toSkip number of bytes to skip.
  356. * @return number of bytes actually skipped.
  357. * @throws IOException if there is a problem reading the file
  358. * @throws IllegalArgumentException if toSkip is negative
  359. * @see InputStream#skip(long)
  360. *
  361. */
  362. public static long skipFully(final InputStream input, final long toSkip) throws IOException {
  363. if (toSkip < 0) {
  364. throw new IllegalArgumentException("Skip count must be non-negative, actual: " + toSkip);
  365. }
  366. if (toSkip == 0) {
  367. return 0L;
  368. }
  369. /*
  370. * N.B. no need to synchronize this because: - we don't care if the buffer is created multiple times (the data
  371. * is ignored) - we always use the same size buffer, so if it it is recreated it will still be OK (if the buffer
  372. * size were variable, we would need to synch. to ensure some other thread did not create a smaller one)
  373. */
  374. if (SKIP_BYTE_BUFFER == null) {
  375. SKIP_BYTE_BUFFER = new byte[SKIP_BUFFER_SIZE];
  376. }
  377. long remain = toSkip;
  378. while (remain > 0) {
  379. // See https://issues.apache.org/jira/browse/IO-203 for why we use read() rather than delegating to skip()
  380. final long n = input.read(SKIP_BYTE_BUFFER, 0, (int) Math.min(remain, SKIP_BUFFER_SIZE));
  381. if (n < 0) { // EOF
  382. break;
  383. }
  384. remain -= n;
  385. }
  386. if (toSkip == remain) {
  387. return -1L;
  388. }
  389. return toSkip - remain;
  390. }
  391. }