Forked from utsengar/EncodeBased64Binary.java
Created
March 22, 2018 23:33
Star
You must be signed in to star a gist
Encode a file to base64 binary in Java
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 org.apache.commons.codec.binary.Base64; | |
private String encodeFileToBase64Binary(String fileName) | |
throws IOException { | |
File file = new File(fileName); | |
byte[] bytes = loadFile(file); | |
byte[] encoded = Base64.encodeBase64(bytes); | |
String encodedString = new String(encoded); | |
return encodedString; | |
} | |
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