Skip to content

Instantly share code, notes, and snippets.

@utsengar
Created October 11, 2011 00:27
Show Gist options
  • Select an option

  • Save utsengar/1276960 to your computer and use it in GitHub Desktop.

Select an option

Save utsengar/1276960 to your computer and use it in GitHub Desktop.
Encode a file to base64 binary in Java
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;
}
@Khyati1992

Khyati1992 commented Feb 1, 2018 •

Copy link
Copy Markdown

@albfan, Hi, I am trying this but getting exception,

java.io.FileNotFoundException: android.content.res.AssetManager$AssetInputStream@197e3549: open failed: ENOENT (No such file or directory)

val file = File(Uri.parse(resources.openRawResource(R.raw.rec1).toString()).toString())
        var encodedBase64: String? = null
        try {
            val fileInputStreamReader = FileInputStream(file)
            val bytes = ByteArray(file.length().toInt())
            fileInputStreamReader.read(bytes)
            val result = Base64.encodeToString(bytes, Base64.DEFAULT)

            println("result--" + result)
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        }

@KingAmada

Copy link
Copy Markdown

A single line solution

byte[] bytes = Base64.getEncoder().encode(Files.readAllBytes(new File("filePath").toPath()));
System.out.print(bytes);

@manishboricha

Copy link
Copy Markdown

This is working like a charm, i am not converting image to string i just needed it in encoded format.....Thanks

@sheliyaparth

Copy link
Copy Markdown

Why not use Base64.encodeBase64String(bytes)?

@Zeriitas

Copy link
Copy Markdown

Guys cmon this was posted 10 years ago...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment