Created
June 26, 2015 15:09
-
-
Save DeveloperPaul123/7f8d4beae160f11b5c85 to your computer and use it in GitHub Desktop.
Simple utility for encoding and decoding files to binary
This file contains hidden or 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; | |
import java.util.Base64; | |
/** | |
* Created by Paul on 6/25/2015. | |
* Encodes and decodes files to and from binary format. | |
*/ | |
public class FileEncoder { | |
/** | |
* Encodes a file to binary. | |
* @param fileName the path to the file | |
* @return an encoded byte array. | |
* @throws IOException | |
*/ | |
public static byte[] encodeFileToBase64Binary(String fileName) | |
throws IOException { | |
File file = new File(fileName); | |
byte[] bytes = loadFile(file); | |
return Base64.getEncoder().encode(bytes); | |
} | |
/** | |
* Decodes a file from binary. | |
* @param fileName the path to the file. | |
* @return a decoded byte array. | |
* @throws IOException | |
*/ | |
public static byte[] decodeFileFromBinary(String fileName) throws IOException { | |
File file = new File(fileName); | |
byte[] bytes = loadFile(file); | |
return Base64.getDecoder().decode(bytes); | |
} | |
/** | |
* Loads a file as an array of bytes. | |
* @param file the file to load. | |
* @return an array of bytes representing the contents of the file. | |
* @throws IOException | |
*/ | |
private static byte[] loadFile(File file) throws IOException { | |
InputStream is = new FileInputStream(file); | |
long length = file.length(); | |
if (length > Integer.MAX_VALUE) { | |
// File is too large | |
} | |
byte[] bytes = new byte[(int)length]; | |
int offset = 0; | |
int numRead = 0; | |
while (offset < bytes.length | |
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) { | |
offset += numRead; | |
} | |
if (offset < bytes.length) { | |
throw new IOException("Could not completely read file "+file.getName()); | |
} | |
is.close(); | |
return bytes; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment