Last active
December 15, 2015 03:39
-
-
Save ThomasOwens/5196168 to your computer and use it in GitHub Desktop.
File reading/writing/parsing utilities.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.IOException; | |
import java.io.InputStream; | |
/** | |
* Utilities for working with files. | |
* | |
* @author Thomas Owens | |
*/ | |
public class FileUtils { | |
/** | |
* Get a byte array that contains the file. Due to the limitations on the | |
* maximum size of an array, if the file is greater than 2147483647 bytes, | |
* or 2.147GB. | |
* | |
* @param file | |
* the file to convert into a byte[] | |
* @return the bytes of the file | |
* @throws IllegalArgumentException | |
* the argument is null, the file does not exist, or the file is | |
* too large to be read into a byte array (> 2147483647 bytes) | |
* @throws IOException | |
* the file could not be read | |
*/ | |
public static byte[] getFileBytes(File file) throws IOException { | |
if (file == null || !file.exists()) { | |
throw new IllegalArgumentException("Specified file must exist."); | |
} | |
long fileLength = file.length(); | |
// Arrays can not be larger than Integer.MAX_VALUE. | |
if (fileLength > Integer.MAX_VALUE) { | |
throw new IllegalArgumentException( | |
"File is too large to read into a byte array"); | |
} | |
InputStream is = new FileInputStream(file); | |
byte[] fileBytes = new byte[(int) fileLength]; | |
int offset = 0; | |
int bytesRead = 0; | |
while (offset < fileBytes.length | |
&& (bytesRead = is.read(fileBytes, offset, fileBytes.length | |
- offset)) > 0) { | |
offset += bytesRead; | |
} | |
if (offset < fileBytes.length) { | |
is.close(); | |
throw new IOException("File not completely read"); | |
} | |
is.close(); | |
return fileBytes; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment