Reads a file of the given expected size from the given input stream, if it will fit into a byte array. This method handles the case where the file size changes between when the size is read and when the contents are read from the stream.
(InputStream in, long expectedSize)
| 168 | |
| 169 | |
| 170 | static byte[] readFile(InputStream in, long expectedSize) throws IOException { |
| 171 | if (expectedSize > Integer.MAX_VALUE) { |
| 172 | throw new OutOfMemoryError("file is too large to fit in a byte array: " + expectedSize + " bytes"); |
| 173 | } |
| 174 | |
| 175 | // some special files may return size 0 but have content, so read |
| 176 | // the file normally in that case |
| 177 | return expectedSize == 0 |
| 178 | ? ByteStreams.toByteArray(in) |
| 179 | : ByteStreams.toByteArray(in, (int) expectedSize); |
| 180 | } |
| 181 | |
| 182 | /** |
| 183 | * Returns a new {@link ByteSink} for writing bytes to the given file. The given {@code modes} |