Skip to content

Instantly share code, notes, and snippets.

@ThomasOwens
Last active December 15, 2015 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ThomasOwens/5196168 to your computer and use it in GitHub Desktop.
Save ThomasOwens/5196168 to your computer and use it in GitHub Desktop.
File reading/writing/parsing utilities.
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