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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  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.*;
  17. import java.nio.ByteBuffer;
  18. import java.nio.channels.ReadableByteChannel;
  19. import java.util.zip.CRC32;
  20. import java.util.zip.Checksum;
  21. import org.apache.poi.EmptyFileException;
  22. import org.apache.poi.POIDocument;
  23. import org.apache.poi.ss.usermodel.Workbook;
  24. public final class IOUtils {
  25. private static final POILogger logger = POILogFactory.getLogger( IOUtils.class );
  26. /**
  27. * The default buffer size to use for the skip() methods.
  28. */
  29. private static final int SKIP_BUFFER_SIZE = 2048;
  30. private static int BYTE_ARRAY_MAX_OVERRIDE = -1;
  31. private static byte[] SKIP_BYTE_BUFFER;
  32. private IOUtils() {
  33. // no instances of this class
  34. }
  35. /**
  36. * If this value is set to > 0, {@link #safelyAllocate(long, int)} will ignore the
  37. * maximum record length parameter. This is designed to allow users to bypass
  38. * the hard-coded maximum record lengths if they are willing to accept the risk
  39. * of an OutOfMemoryException.
  40. *
  41. * @param maxOverride The number of bytes that should be possible to be allocated in one step.
  42. * @since 4.0.0
  43. */
  44. @SuppressWarnings("unused")
  45. public static void setByteArrayMaxOverride(int maxOverride) {
  46. BYTE_ARRAY_MAX_OVERRIDE = maxOverride;
  47. }
  48. /**
  49. * Peeks at the first 8 bytes of the stream. Returns those bytes, but
  50. * with the stream unaffected. Requires a stream that supports mark/reset,
  51. * or a PushbackInputStream. If the stream has >0 but <8 bytes,
  52. * remaining bytes will be zero.
  53. * @throws EmptyFileException if the stream is empty
  54. */
  55. public static byte[] peekFirst8Bytes(InputStream stream) throws IOException, EmptyFileException {
  56. return peekFirstNBytes(stream, 8);
  57. }
  58. /**
  59. * Peeks at the first N bytes of the stream. Returns those bytes, but
  60. * with the stream unaffected. Requires a stream that supports mark/reset,
  61. * or a PushbackInputStream. If the stream has >0 but <N bytes,
  62. * remaining bytes will be zero.
  63. * @throws EmptyFileException if the stream is empty
  64. */
  65. public static byte[] peekFirstNBytes(InputStream stream, int limit) throws IOException, EmptyFileException {
  66. stream.mark(limit);
  67. ByteArrayOutputStream bos = new ByteArrayOutputStream(limit);
  68. copy(new BoundedInputStream(stream, limit), bos);
  69. int readBytes = bos.size();
  70. if (readBytes == 0) {
  71. throw new EmptyFileException();
  72. }
  73. if (readBytes < limit) {
  74. bos.write(new byte[limit-readBytes]);
  75. }
  76. byte peekedBytes[] = bos.toByteArray();
  77. if(stream instanceof PushbackInputStream) {
  78. PushbackInputStream pin = (PushbackInputStream)stream;
  79. pin.unread(peekedBytes, 0, readBytes);
  80. } else {
  81. stream.reset();
  82. }
  83. return peekedBytes;
  84. }
  85. /**
  86. * Reads all the data from the input stream, and returns the bytes read.
  87. *
  88. * @param stream The byte stream of data to read.
  89. * @return A byte array with the read bytes.
  90. * @throws IOException If reading data fails or EOF is encountered too early for the given length.
  91. */
  92. public static byte[] toByteArray(InputStream stream) throws IOException {
  93. return toByteArray(stream, Integer.MAX_VALUE);
  94. }
  95. /**
  96. * Reads up to {@code length} bytes from the input stream, and returns the bytes read.
  97. *
  98. * @param stream The byte stream of data to read.
  99. * @param length The maximum length to read, use Integer.MAX_VALUE to read the stream
  100. * until EOF.
  101. * @return A byte array with the read bytes.
  102. * @throws IOException If reading data fails or EOF is encountered too early for the given length.
  103. */
  104. public static byte[] toByteArray(InputStream stream, final int length) throws IOException {
  105. return toByteArray(stream, length, Integer.MAX_VALUE);
  106. }
  107. /**
  108. * Reads up to {@code length} bytes from the input stream, and returns the bytes read.
  109. *
  110. * @param stream The byte stream of data to read.
  111. * @param length The maximum length to read, use {@link Integer#MAX_VALUE} to read the stream
  112. * until EOF
  113. * @param maxLength if the input is equal to/longer than {@code maxLength} bytes,
  114. * then throw an {@link IOException} complaining about the length.
  115. * use {@link Integer#MAX_VALUE} to disable the check
  116. * @return A byte array with the read bytes.
  117. * @throws IOException If reading data fails or EOF is encountered too early for the given length.
  118. */
  119. public static byte[] toByteArray(InputStream stream, final long length, final int maxLength) throws IOException {
  120. if (length < 0L || maxLength < 0L) {
  121. throw new RecordFormatException("Can't allocate an array of length < 0");
  122. }
  123. if (length > (long)Integer.MAX_VALUE) {
  124. throw new RecordFormatException("Can't allocate an array > "+Integer.MAX_VALUE);
  125. }
  126. checkLength(length, maxLength);
  127. final int len = Math.min((int)length, maxLength);
  128. ByteArrayOutputStream baos = new ByteArrayOutputStream(len == Integer.MAX_VALUE ? 4096 : len);
  129. byte[] buffer = new byte[4096];
  130. int totalBytes = 0, readBytes;
  131. do {
  132. readBytes = stream.read(buffer, 0, Math.min(buffer.length, len-totalBytes));
  133. totalBytes += Math.max(readBytes,0);
  134. if (readBytes > 0) {
  135. baos.write(buffer, 0, readBytes);
  136. }
  137. } while (totalBytes < len && readBytes > -1);
  138. if (maxLength != Integer.MAX_VALUE && totalBytes == maxLength) {
  139. throw new IOException("MaxLength ("+maxLength+") reached - stream seems to be invalid.");
  140. }
  141. if (len != Integer.MAX_VALUE && totalBytes < len) {
  142. throw new EOFException("unexpected EOF - expected len: "+len+" - actual len: "+totalBytes);
  143. }
  144. return baos.toByteArray();
  145. }
  146. private static void checkLength(long length, int maxLength) {
  147. if (BYTE_ARRAY_MAX_OVERRIDE > 0) {
  148. if (length > BYTE_ARRAY_MAX_OVERRIDE) {
  149. throwRFE(length, BYTE_ARRAY_MAX_OVERRIDE);
  150. }
  151. } else if (length > maxLength) {
  152. throwRFE(length, maxLength);
  153. }
  154. }
  155. /**
  156. * Returns an array (that shouldn't be written to!) of the
  157. * ByteBuffer. Will be of the requested length, or possibly
  158. * longer if that's easier.
  159. */
  160. public static byte[] toByteArray(ByteBuffer buffer, int length) {
  161. if(buffer.hasArray() && buffer.arrayOffset() == 0) {
  162. // The backing array should work out fine for us
  163. return buffer.array();
  164. }
  165. byte[] data = new byte[length];
  166. buffer.get(data);
  167. return data;
  168. }
  169. /**
  170. * Helper method, just calls <tt>readFully(in, b, 0, b.length)</tt>
  171. */
  172. public static int readFully(InputStream in, byte[] b) throws IOException {
  173. return readFully(in, b, 0, b.length);
  174. }
  175. /**
  176. * <p>Same as the normal {@link InputStream#read(byte[], int, int)}, but tries to ensure
  177. * that the entire len number of bytes is read.</p>
  178. *
  179. * <p>If the end of file is reached before any bytes are read, returns <tt>-1</tt>. If
  180. * the end of the file is reached after some bytes are read, returns the
  181. * number of bytes read. If the end of the file isn't reached before <tt>len</tt>
  182. * bytes have been read, will return <tt>len</tt> bytes.</p>
  183. *
  184. * @param in the stream from which the data is read.
  185. * @param b the buffer into which the data is read.
  186. * @param off the start offset in array <tt>b</tt> at which the data is written.
  187. * @param len the maximum number of bytes to read.
  188. */
  189. public static int readFully(InputStream in, byte[] b, int off, int len) throws IOException {
  190. int total = 0;
  191. while (true) {
  192. int got = in.read(b, off + total, len - total);
  193. if (got < 0) {
  194. return (total == 0) ? -1 : total;
  195. }
  196. total += got;
  197. if (total == len) {
  198. return total;
  199. }
  200. }
  201. }
  202. /**
  203. * Same as the normal <tt>channel.read(b)</tt>, but tries to ensure
  204. * that the buffer is filled completely if possible, i.e. b.remaining()
  205. * returns 0.
  206. * <p>
  207. * If the end of file is reached before any bytes are read, returns -1. If
  208. * the end of the file is reached after some bytes are read, returns the
  209. * number of bytes read. If the end of the file isn't reached before the
  210. * buffer has no more remaining capacity, will return the number of bytes
  211. * that were read.
  212. */
  213. public static int readFully(ReadableByteChannel channel, ByteBuffer b) throws IOException {
  214. int total = 0;
  215. while (true) {
  216. int got = channel.read(b);
  217. if (got < 0) {
  218. return (total == 0) ? -1 : total;
  219. }
  220. total += got;
  221. if (total == b.capacity() || b.position() == b.capacity()) {
  222. return total;
  223. }
  224. }
  225. }
  226. /**
  227. * 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.
  228. * This will attempt to close the output stream at the end even if there was a problem writing the document to the stream.
  229. *
  230. * If you are using Java 7 or higher, you may prefer to use a try-with-resources statement instead.
  231. * This function exists for Java 6 code.
  232. *
  233. * @param doc a writeable document to write to the output stream
  234. * @param out the output stream that the document is written to
  235. * @throws IOException thrown on errors writing to the stream
  236. *
  237. * @deprecated since 4.0, use try-with-resources, will be removed in 4.2
  238. */
  239. @Deprecated
  240. @Removal(version="4.2")
  241. public static void write(POIDocument doc, OutputStream out) throws IOException {
  242. try {
  243. doc.write(out);
  244. } finally {
  245. closeQuietly(out);
  246. }
  247. }
  248. /**
  249. * Write a ({@link org.apache.poi.ss.usermodel.Workbook}) to an output stream and close the output stream.
  250. * This will attempt to close the output stream at the end even if there was a problem writing the document to the stream.
  251. *
  252. * If you are using Java 7 or higher, you may prefer to use a try-with-resources statement instead.
  253. * This function exists for Java 6 code.
  254. *
  255. * @param doc a writeable document to write to the output stream
  256. * @param out the output stream that the document is written to
  257. * @throws IOException thrown on errors writing to the stream
  258. *
  259. * @deprecated since 4.0, use try-with-resources, will be removed in 4.2
  260. */
  261. @Deprecated
  262. @Removal(version="4.2")
  263. public static void write(Workbook doc, OutputStream out) throws IOException {
  264. try {
  265. doc.write(out);
  266. } finally {
  267. closeQuietly(out);
  268. }
  269. }
  270. /**
  271. * 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.
  272. * This will attempt to close the output stream at the end even if there was a problem writing the document to the stream.
  273. * This will also attempt to close the document, even if an error occurred while writing the document or closing the output stream.
  274. *
  275. * If you are using Java 7 or higher, you may prefer to use a try-with-resources statement instead.
  276. * This function exists for Java 6 code.
  277. *
  278. * @param doc a writeable and closeable document to write to the output stream, then close
  279. * @param out the output stream that the document is written to
  280. * @throws IOException thrown on errors writing to the stream
  281. *
  282. * @deprecated since 4.0, use try-with-resources, will be removed in 4.2
  283. */
  284. @Deprecated
  285. @Removal(version="4.2")
  286. public static void writeAndClose(POIDocument doc, OutputStream out) throws IOException {
  287. try {
  288. write(doc, out);
  289. } finally {
  290. closeQuietly(doc);
  291. }
  292. }
  293. /**
  294. * Like {@link #writeAndClose(POIDocument, OutputStream)}, but for writing to a File instead of an OutputStream.
  295. * This will attempt to close the document, even if an error occurred while writing the document.
  296. *
  297. * If you are using Java 7 or higher, you may prefer to use a try-with-resources statement instead.
  298. * This function exists for Java 6 code.
  299. *
  300. * @param doc a writeable and closeable document to write to the output file, then close
  301. * @param out the output file that the document is written to
  302. * @throws IOException thrown on errors writing to the stream
  303. *
  304. * @deprecated since 4.0, use try-with-resources, will be removed in 4.2
  305. */
  306. @Deprecated
  307. @Removal(version="4.2")
  308. public static void writeAndClose(POIDocument doc, File out) throws IOException {
  309. try {
  310. doc.write(out);
  311. } finally {
  312. closeQuietly(doc);
  313. }
  314. }
  315. /**
  316. * Like {@link #writeAndClose(POIDocument, File)}, but for writing a POI Document in place (to the same file that it was opened from).
  317. * This will attempt to close the document, even if an error occurred while writing the document.
  318. *
  319. * If you are using Java 7 or higher, you may prefer to use a try-with-resources statement instead.
  320. * This function exists for Java 6 code.
  321. *
  322. * @param doc a writeable document to write in-place
  323. * @throws IOException thrown on errors writing to the file
  324. *
  325. * @deprecated since 4.0, use try-with-resources, will be removed in 4.2
  326. */
  327. @Deprecated
  328. @Removal(version="4.2")
  329. public static void writeAndClose(POIDocument doc) throws IOException {
  330. try {
  331. doc.write();
  332. } finally {
  333. closeQuietly(doc);
  334. }
  335. }
  336. // Since the Workbook interface doesn't derive from POIDocument
  337. // We'll likely need one of these for each document container interface
  338. /**
  339. *
  340. * @deprecated since 4.0, use try-with-resources, will be removed in 4.2
  341. */
  342. @Deprecated
  343. @Removal(version="4.2")
  344. public static void writeAndClose(Workbook doc, OutputStream out) throws IOException {
  345. try {
  346. doc.write(out);
  347. } finally {
  348. closeQuietly(doc);
  349. }
  350. }
  351. /**
  352. * Copies all the data from the given InputStream to the OutputStream. It
  353. * leaves both streams open, so you will still need to close them once done.
  354. *
  355. * @param inp The {@link InputStream} which provides the data
  356. * @param out The {@link OutputStream} to write the data to
  357. * @return the amount of bytes copied
  358. *
  359. * @throws IOException If copying the data fails.
  360. */
  361. public static long copy(InputStream inp, OutputStream out) throws IOException {
  362. return copy(inp, out, -1);
  363. }
  364. /**
  365. * Copies all the data from the given InputStream to the OutputStream. It
  366. * leaves both streams open, so you will still need to close them once done.
  367. *
  368. * @param inp The {@link InputStream} which provides the data
  369. * @param out The {@link OutputStream} to write the data to
  370. * @param limit limit the copied bytes - use {@code -1} for no limit
  371. * @return the amount of bytes copied
  372. *
  373. * @throws IOException If copying the data fails.
  374. */
  375. public static long copy(InputStream inp, OutputStream out, long limit) throws IOException {
  376. final byte[] buff = new byte[4096];
  377. long totalCount = 0;
  378. int readBytes = -1;
  379. do {
  380. int todoBytes = (int)((limit < 0) ? buff.length : Math.min(limit-totalCount, buff.length));
  381. if (todoBytes > 0) {
  382. readBytes = inp.read(buff, 0, todoBytes);
  383. if (readBytes > 0) {
  384. out.write(buff, 0, readBytes);
  385. totalCount += readBytes;
  386. }
  387. }
  388. } while (readBytes >= 0 && (limit == -1 || totalCount < limit));
  389. return totalCount;
  390. }
  391. /**
  392. * Copy the contents of the stream to a new file.
  393. *
  394. * @param srcStream The {@link InputStream} which provides the data
  395. * @param destFile The file where the data should be stored
  396. * @return the amount of bytes copied
  397. *
  398. * @throws IOException If the target directory does not exist and cannot be created
  399. * or if copying the data fails.
  400. */
  401. public static long copy(InputStream srcStream, File destFile) throws IOException {
  402. File destDirectory = destFile.getParentFile();
  403. if (!(destDirectory.exists() || destDirectory.mkdirs())) {
  404. throw new RuntimeException("Can't create destination directory: "+destDirectory);
  405. }
  406. try (OutputStream destStream = new FileOutputStream(destFile)) {
  407. return IOUtils.copy(srcStream, destStream);
  408. }
  409. }
  410. /**
  411. * Calculate checksum on input data
  412. */
  413. public static long calculateChecksum(byte[] data) {
  414. Checksum sum = new CRC32();
  415. sum.update(data, 0, data.length);
  416. return sum.getValue();
  417. }
  418. /**
  419. * Calculate checksum on all the data read from input stream.
  420. *
  421. * This should be more efficient than the equivalent code
  422. * {@code IOUtils.calculateChecksum(IOUtils.toByteArray(stream))}
  423. */
  424. public static long calculateChecksum(InputStream stream) throws IOException {
  425. Checksum sum = new CRC32();
  426. byte[] buf = new byte[4096];
  427. int count;
  428. while ((count = stream.read(buf)) != -1) {
  429. if (count > 0) {
  430. sum.update(buf, 0, count);
  431. }
  432. }
  433. return sum.getValue();
  434. }
  435. /**
  436. * Quietly (no exceptions) close Closable resource. In case of error it will
  437. * be printed to {@link IOUtils} class logger.
  438. *
  439. * @param closeable
  440. * resource to close
  441. */
  442. public static void closeQuietly( final Closeable closeable ) {
  443. // no need to log a NullPointerException here
  444. if(closeable == null) {
  445. return;
  446. }
  447. try {
  448. closeable.close();
  449. } catch ( Exception exc ) {
  450. logger.log( POILogger.ERROR, "Unable to close resource: " + exc,
  451. exc );
  452. }
  453. }
  454. /**
  455. * Skips bytes from an input byte stream.
  456. * This implementation guarantees that it will read as many bytes
  457. * as possible before giving up; this may not always be the case for
  458. * skip() implementations in subclasses of {@link InputStream}.
  459. * <p>
  460. * Note that the implementation uses {@link InputStream#read(byte[], int, int)} rather
  461. * than delegating to {@link InputStream#skip(long)}.
  462. * This means that the method may be considerably less efficient than using the actual skip implementation,
  463. * this is done to guarantee that the correct number of bytes are skipped.
  464. * </p>
  465. * <p>
  466. * This mimics POI's {@link #readFully(InputStream, byte[])}.
  467. * If the end of file is reached before any bytes are read, returns <tt>-1</tt>. If
  468. * the end of the file is reached after some bytes are read, returns the
  469. * number of bytes read. If the end of the file isn't reached before <tt>len</tt>
  470. * bytes have been read, will return <tt>len</tt> bytes.</p>
  471. * </p>
  472. * <p>
  473. * Copied nearly verbatim from commons-io 41a3e9c
  474. * </p>
  475. *
  476. * @param input byte stream to skip
  477. * @param toSkip number of bytes to skip.
  478. * @return number of bytes actually skipped.
  479. * @throws IOException if there is a problem reading the file
  480. * @throws IllegalArgumentException if toSkip is negative
  481. * @see InputStream#skip(long)
  482. *
  483. */
  484. public static long skipFully(final InputStream input, final long toSkip) throws IOException {
  485. if (toSkip < 0) {
  486. throw new IllegalArgumentException("Skip count must be non-negative, actual: " + toSkip);
  487. }
  488. if (toSkip == 0) {
  489. return 0L;
  490. }
  491. /*
  492. * N.B. no need to synchronize this because: - we don't care if the buffer is created multiple times (the data
  493. * is ignored) - we always use the same size buffer, so if it it is recreated it will still be OK (if the buffer
  494. * size were variable, we would need to synch. to ensure some other thread did not create a smaller one)
  495. */
  496. if (SKIP_BYTE_BUFFER == null) {
  497. SKIP_BYTE_BUFFER = new byte[SKIP_BUFFER_SIZE];
  498. }
  499. long remain = toSkip;
  500. while (remain > 0) {
  501. // See https://issues.apache.org/jira/browse/IO-203 for why we use read() rather than delegating to skip()
  502. final long n = input.read(SKIP_BYTE_BUFFER, 0, (int) Math.min(remain, SKIP_BUFFER_SIZE));
  503. if (n < 0) { // EOF
  504. break;
  505. }
  506. remain -= n;
  507. }
  508. if (toSkip == remain) {
  509. return -1L;
  510. }
  511. return toSkip - remain;
  512. }
  513. public static byte[] safelyAllocate(long length, int maxLength) {
  514. if (length < 0L) {
  515. throw new RecordFormatException("Can't allocate an array of length < 0");
  516. }
  517. if (length > (long)Integer.MAX_VALUE) {
  518. throw new RecordFormatException("Can't allocate an array > "+Integer.MAX_VALUE);
  519. }
  520. checkLength(length, maxLength);
  521. return new byte[(int)length];
  522. }
  523. /**
  524. * Simple utility function to check that you haven't hit EOF
  525. * when reading a byte.
  526. *
  527. * @param is inputstream to read
  528. * @return byte read, unless
  529. * @throws IOException on IOException or EOF if -1 is read
  530. */
  531. public static int readByte(InputStream is) throws IOException {
  532. int b = is.read();
  533. if (b == -1) {
  534. throw new EOFException();
  535. }
  536. return b;
  537. }
  538. private static void throwRFE(long length, int maxLength) {
  539. throw new RecordFormatException("Tried to allocate an array of length "+length +
  540. ", but "+ maxLength+" is the maximum for this record type.\n" +
  541. "If the file is not corrupt, please open an issue on bugzilla to request \n" +
  542. "increasing the maximum allowable size for this record type.\n"+
  543. "As a temporary workaround, consider setting a higher override value with " +
  544. "IOUtils.setByteArrayMaxOverride()");
  545. }
  546. }