Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

IOUtils.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. private IOUtils() {
  33. // no instances of this class
  34. }
  35. /**
  36. * Peeks at the first 8 bytes of the stream. Returns those bytes, but
  37. * with the stream unaffected. Requires a stream that supports mark/reset,
  38. * or a PushbackInputStream. If the stream has >0 but <8 bytes,
  39. * remaining bytes will be zero.
  40. * @throws EmptyFileException if the stream is empty
  41. */
  42. public static byte[] peekFirst8Bytes(InputStream stream) throws IOException, EmptyFileException {
  43. return peekFirstNBytes(stream, 8);
  44. }
  45. /**
  46. * Peeks at the first N bytes of the stream. Returns those bytes, but
  47. * with the stream unaffected. Requires a stream that supports mark/reset,
  48. * or a PushbackInputStream. If the stream has >0 but <N bytes,
  49. * remaining bytes will be zero.
  50. * @throws EmptyFileException if the stream is empty
  51. */
  52. public static byte[] peekFirstNBytes(InputStream stream, int limit) throws IOException, EmptyFileException {
  53. stream.mark(limit);
  54. ByteArrayOutputStream bos = new ByteArrayOutputStream(limit);
  55. copy(new BoundedInputStream(stream, limit), bos);
  56. int readBytes = bos.size();
  57. if (readBytes == 0) {
  58. throw new EmptyFileException();
  59. }
  60. if (readBytes < limit) {
  61. bos.write(new byte[limit-readBytes]);
  62. }
  63. byte peekedBytes[] = bos.toByteArray();
  64. if(stream instanceof PushbackInputStream) {
  65. PushbackInputStream pin = (PushbackInputStream)stream;
  66. pin.unread(peekedBytes, 0, readBytes);
  67. } else {
  68. stream.reset();
  69. }
  70. return peekedBytes;
  71. }
  72. /**
  73. * Reads all the data from the input stream, and returns the bytes read.
  74. */
  75. public static byte[] toByteArray(InputStream stream) throws IOException {
  76. return toByteArray(stream, Integer.MAX_VALUE);
  77. }
  78. /**
  79. * Reads up to {@code length} bytes from the input stream, and returns the bytes read.
  80. */
  81. public static byte[] toByteArray(InputStream stream, int length) throws IOException {
  82. ByteArrayOutputStream baos = new ByteArrayOutputStream(length == Integer.MAX_VALUE ? 4096 : length);
  83. byte[] buffer = new byte[4096];
  84. int totalBytes = 0, readBytes;
  85. do {
  86. readBytes = stream.read(buffer, 0, Math.min(buffer.length, length-totalBytes));
  87. totalBytes += Math.max(readBytes,0);
  88. if (readBytes > 0) {
  89. baos.write(buffer, 0, readBytes);
  90. }
  91. } while (totalBytes < length && readBytes > -1);
  92. if (length != Integer.MAX_VALUE && totalBytes < length) {
  93. throw new IOException("unexpected EOF");
  94. }
  95. return baos.toByteArray();
  96. }
  97. /**
  98. * Returns an array (that shouldn't be written to!) of the
  99. * ByteBuffer. Will be of the requested length, or possibly
  100. * longer if that's easier.
  101. */
  102. public static byte[] toByteArray(ByteBuffer buffer, int length) {
  103. if(buffer.hasArray() && buffer.arrayOffset() == 0) {
  104. // The backing array should work out fine for us
  105. return buffer.array();
  106. }
  107. byte[] data = new byte[length];
  108. buffer.get(data);
  109. return data;
  110. }
  111. /**
  112. * Helper method, just calls <tt>readFully(in, b, 0, b.length)</tt>
  113. */
  114. public static int readFully(InputStream in, byte[] b) throws IOException {
  115. return readFully(in, b, 0, b.length);
  116. }
  117. /**
  118. * <p>Same as the normal {@link InputStream#read(byte[], int, int)}, but tries to ensure
  119. * that the entire len number of bytes is read.</p>
  120. *
  121. * <p>If the end of file is reached before any bytes are read, returns <tt>-1</tt>. If
  122. * the end of the file is reached after some bytes are read, returns the
  123. * number of bytes read. If the end of the file isn't reached before <tt>len</tt>
  124. * bytes have been read, will return <tt>len</tt> bytes.</p>
  125. *
  126. * @param in the stream from which the data is read.
  127. * @param b the buffer into which the data is read.
  128. * @param off the start offset in array <tt>b</tt> at which the data is written.
  129. * @param len the maximum number of bytes to read.
  130. */
  131. public static int readFully(InputStream in, byte[] b, int off, int len) throws IOException {
  132. int total = 0;
  133. while (true) {
  134. int got = in.read(b, off + total, len - total);
  135. if (got < 0) {
  136. return (total == 0) ? -1 : total;
  137. }
  138. total += got;
  139. if (total == len) {
  140. return total;
  141. }
  142. }
  143. }
  144. /**
  145. * Same as the normal <tt>channel.read(b)</tt>, but tries to ensure
  146. * that the buffer is filled completely if possible, i.e. b.remaining()
  147. * returns 0.
  148. * <p>
  149. * If the end of file is reached before any bytes are read, returns -1. If
  150. * the end of the file is reached after some bytes are read, returns the
  151. * number of bytes read. If the end of the file isn't reached before the
  152. * buffer has no more remaining capacity, will return the number of bytes
  153. * that were read.
  154. */
  155. public static int readFully(ReadableByteChannel channel, ByteBuffer b) throws IOException {
  156. int total = 0;
  157. while (true) {
  158. int got = channel.read(b);
  159. if (got < 0) {
  160. return (total == 0) ? -1 : total;
  161. }
  162. total += got;
  163. if (total == b.capacity() || b.position() == b.capacity()) {
  164. return total;
  165. }
  166. }
  167. }
  168. /**
  169. * 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.
  170. * This will attempt to close the output stream at the end even if there was a problem writing the document to the stream.
  171. *
  172. * If you are using Java 7 or higher, you may prefer to use a try-with-resources statement instead.
  173. * This function exists for Java 6 code.
  174. *
  175. * @param doc a writeable document to write to the output stream
  176. * @param out the output stream that the document is written to
  177. * @throws IOException
  178. */
  179. public static void write(POIDocument doc, OutputStream out) throws IOException {
  180. try {
  181. doc.write(out);
  182. } finally {
  183. closeQuietly(out);
  184. }
  185. }
  186. /**
  187. * Write a ({@link org.apache.poi.ss.usermodel.Workbook}) to an output stream and close the output stream.
  188. * This will attempt to close the output stream at the end even if there was a problem writing the document to the stream.
  189. *
  190. * If you are using Java 7 or higher, you may prefer to use a try-with-resources statement instead.
  191. * This function exists for Java 6 code.
  192. *
  193. * @param doc a writeable document to write to the output stream
  194. * @param out the output stream that the document is written to
  195. * @throws IOException
  196. */
  197. public static void write(Workbook doc, OutputStream out) throws IOException {
  198. try {
  199. doc.write(out);
  200. } finally {
  201. closeQuietly(out);
  202. }
  203. }
  204. /**
  205. * 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.
  206. * This will attempt to close the output stream at the end even if there was a problem writing the document to the stream.
  207. * This will also attempt to close the document, even if an error occurred while writing the document or closing the output stream.
  208. *
  209. * If you are using Java 7 or higher, you may prefer to use a try-with-resources statement instead.
  210. * This function exists for Java 6 code.
  211. *
  212. * @param doc a writeable and closeable document to write to the output stream, then close
  213. * @param out the output stream that the document is written to
  214. * @throws IOException
  215. */
  216. public static void writeAndClose(POIDocument doc, OutputStream out) throws IOException {
  217. try {
  218. write(doc, out);
  219. } finally {
  220. closeQuietly(doc);
  221. }
  222. }
  223. /**
  224. * Like {@link #writeAndClose(POIDocument, OutputStream)}, but for writing to a File instead of an OutputStream.
  225. * This will attempt to close the document, even if an error occurred while writing the document.
  226. *
  227. * If you are using Java 7 or higher, you may prefer to use a try-with-resources statement instead.
  228. * This function exists for Java 6 code.
  229. *
  230. * @param doc a writeable and closeable document to write to the output file, then close
  231. * @param out the output file that the document is written to
  232. * @throws IOException
  233. */
  234. public static void writeAndClose(POIDocument doc, File out) throws IOException {
  235. try {
  236. doc.write(out);
  237. } finally {
  238. closeQuietly(doc);
  239. }
  240. }
  241. /**
  242. * Like {@link #writeAndClose(POIDocument, File)}, but for writing a POI Document in place (to the same file that it was opened from).
  243. * This will attempt to close the document, even if an error occurred while writing the document.
  244. *
  245. * If you are using Java 7 or higher, you may prefer to use a try-with-resources statement instead.
  246. * This function exists for Java 6 code.
  247. *
  248. * @param doc a writeable document to write in-place
  249. * @throws IOException
  250. */
  251. public static void writeAndClose(POIDocument doc) throws IOException {
  252. try {
  253. doc.write();
  254. } finally {
  255. closeQuietly(doc);
  256. }
  257. }
  258. // Since the Workbook interface doesn't derive from POIDocument
  259. // We'll likely need one of these for each document container interface
  260. public static void writeAndClose(Workbook doc, OutputStream out) throws IOException {
  261. try {
  262. doc.write(out);
  263. } finally {
  264. closeQuietly(doc);
  265. }
  266. }
  267. /**
  268. * Copies all the data from the given InputStream to the OutputStream. It
  269. * leaves both streams open, so you will still need to close them once done.
  270. */
  271. public static void copy(InputStream inp, OutputStream out) throws IOException {
  272. byte[] buff = new byte[4096];
  273. int count;
  274. while ((count = inp.read(buff)) != -1) {
  275. if (count > 0) {
  276. out.write(buff, 0, count);
  277. }
  278. }
  279. }
  280. /**
  281. * Calculate checksum on input data
  282. */
  283. public static long calculateChecksum(byte[] data) {
  284. Checksum sum = new CRC32();
  285. sum.update(data, 0, data.length);
  286. return sum.getValue();
  287. }
  288. /**
  289. * Calculate checksum on all the data read from input stream.
  290. *
  291. * This should be more efficient than the equivalent code
  292. * {@code IOUtils.calculateChecksum(IOUtils.toByteArray(stream))}
  293. */
  294. public static long calculateChecksum(InputStream stream) throws IOException {
  295. Checksum sum = new CRC32();
  296. byte[] buf = new byte[4096];
  297. int count;
  298. while ((count = stream.read(buf)) != -1) {
  299. if (count > 0) {
  300. sum.update(buf, 0, count);
  301. }
  302. }
  303. return sum.getValue();
  304. }
  305. /**
  306. * Quietly (no exceptions) close Closable resource. In case of error it will
  307. * be printed to {@link IOUtils} class logger.
  308. *
  309. * @param closeable
  310. * resource to close
  311. */
  312. public static void closeQuietly( final Closeable closeable ) {
  313. // no need to log a NullPointerException here
  314. if(closeable == null) {
  315. return;
  316. }
  317. try {
  318. closeable.close();
  319. } catch ( Exception exc ) {
  320. logger.log( POILogger.ERROR, "Unable to close resource: " + exc,
  321. exc );
  322. }
  323. }
  324. /**
  325. * Skips bytes from a stream. Returns -1L if len > available() or if EOF was hit before
  326. * the end of the stream.
  327. *
  328. * @param in inputstream
  329. * @param len length to skip
  330. * @return number of bytes skipped
  331. * @throws IOException on IOException
  332. */
  333. public static long skipFully(InputStream in, long len) throws IOException {
  334. long total = 0;
  335. while (true) {
  336. long toSkip = len-total;
  337. //check that the stream has the toSkip available
  338. //FileInputStream can mis-report 20k skipped on a 10k file
  339. if (toSkip > in.available()) {
  340. return -1L;
  341. }
  342. long got = in.skip(len-total);
  343. if (got < 0) {
  344. return -1L;
  345. } else if (got == 0) {
  346. got = fallBackToReadFully(len-total, in);
  347. if (got < 0) {
  348. return -1L;
  349. }
  350. }
  351. total += got;
  352. if (total == len) {
  353. return total;
  354. }
  355. }
  356. }
  357. //an InputStream can return 0 whether or not it hits EOF
  358. //if it returns 0, back off to readFully to test for -1
  359. private static long fallBackToReadFully(long lenToRead, InputStream in) throws IOException {
  360. byte[] buffer = new byte[8192];
  361. long readSoFar = 0;
  362. while (true) {
  363. int toSkip = (lenToRead > Integer.MAX_VALUE ||
  364. (lenToRead-readSoFar) > buffer.length) ? buffer.length : (int)(lenToRead-readSoFar);
  365. long readNow = readFully(in, buffer, 0, toSkip);
  366. if (readNow < toSkip) {
  367. return -1L;
  368. }
  369. readSoFar += readNow;
  370. if (readSoFar == lenToRead) {
  371. return readSoFar;
  372. }
  373. }
  374. }
  375. }