| 3364 |
chandransh |
1 |
package in.shop2020.support.utils;
|
|
|
2 |
|
|
|
3 |
import java.io.File;
|
|
|
4 |
import java.io.FileInputStream;
|
|
|
5 |
import java.io.IOException;
|
|
|
6 |
|
|
|
7 |
public class FileUtils {
|
|
|
8 |
/**
|
|
|
9 |
* Reads a file and converts its contents to a byte array.
|
|
|
10 |
*
|
|
|
11 |
* @param file
|
|
|
12 |
* Name of the file to process
|
|
|
13 |
* @return the contents of the file in a byte array.
|
|
|
14 |
* @throws IOException
|
|
|
15 |
* if the file could not be found or read or is too big to
|
|
|
16 |
* convert to a byte array.
|
|
|
17 |
*/
|
|
|
18 |
public static byte[] getBytesFromFile(File file) throws IOException {
|
|
|
19 |
FileInputStream is = new FileInputStream(file);
|
|
|
20 |
|
|
|
21 |
// Get the size of the file
|
|
|
22 |
long length = file.length();
|
|
|
23 |
|
|
|
24 |
// You cannot create an array using a long type.
|
|
|
25 |
// It needs to be an int type.
|
|
|
26 |
// Before converting to an int type, check
|
|
|
27 |
// to ensure that file is not larger than Integer.MAX_VALUE.
|
|
|
28 |
if (length > Integer.MAX_VALUE) {
|
|
|
29 |
// File is too large
|
|
|
30 |
throw new IOException(file.getName() + " is too large to stream");
|
|
|
31 |
}
|
|
|
32 |
|
|
|
33 |
// Create the byte array to hold the data
|
|
|
34 |
byte[] bytes = new byte[(int)length];
|
|
|
35 |
|
|
|
36 |
// Read in the bytes
|
|
|
37 |
int offset = 0;
|
|
|
38 |
int numRead = 0;
|
|
|
39 |
while (offset < bytes.length
|
|
|
40 |
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
|
|
|
41 |
offset += numRead;
|
|
|
42 |
}
|
|
|
43 |
|
|
|
44 |
// Ensure all the bytes have been read in
|
|
|
45 |
if (offset < bytes.length) {
|
|
|
46 |
throw new IOException("Could not completely read file "+file.getName());
|
|
|
47 |
}
|
|
|
48 |
|
|
|
49 |
// Close the input stream and return bytes
|
|
|
50 |
is.close();
|
|
|
51 |
return bytes;
|
|
|
52 |
}
|
|
|
53 |
}
|