Skip to content

Instantly share code, notes, and snippets.

@utsengar
Created October 11, 2011 00:27
Show Gist options
  • Star 35 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save utsengar/1276960 to your computer and use it in GitHub Desktop.
Save utsengar/1276960 to your computer and use it in GitHub Desktop.
Encode a file to base64 binary in Java
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;
}
@tbruyelle
Copy link

OutOfMemory can occur here new String(encoded)

@LulzAugusto
Copy link

Why not use Base64.encodeBase64String(bytes)?

@ImranTamboli
Copy link

hey...thank you so so much brother.its really helpful for me ...:) just need one change in code Base64.encodeBase64String(bytes).. thanx again

@hstarkar87
Copy link

Encode a file into Base64 format
http://www.codesolution.org/?p=299

@albfan
Copy link

albfan commented Nov 10, 2015

That solution didn't work.

Base64.encodeBase64(bytes).toString() outputs [B@c163956

Here you are a minimal working implementation

        File originalFile = new File("signature.jpg");
        String encodedBase64 = null;
        try {
            FileInputStream fileInputStreamReader = new FileInputStream(originalFile);
            byte[] bytes = new byte[(int)originalFile.length()];
            fileInputStreamReader.read(bytes);
            encodedBase64 = new String(Base64.encodeBase64(bytes));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

@RajeswariLakshman
Copy link

Problem solved. Gave file name with location .
String attachment_string= encodeFileToBase64Binary("C:\file_location"+fileName);

@DhineshManthiram
Copy link

Thanks albfan

@FherPie
Copy link

FherPie commented Aug 23, 2016

It doesn't mark error if I add this library to my project: https://commons.apache.org/proper/commons-codec/ I haven't tested yet.

@tnpradeep
Copy link

Hi,

I have an HTTP API which returns zip file contents as response which i have encoded in base 64 and passing it to my UI layer written in javascript.
But when I decode the contents using atob functoin in javascript, the contents of zip file is corrupted.

Please help me in solving this problem.

@LightMan
Copy link

LightMan commented Oct 4, 2017

Mine based on @albfan code:

private String encodeFileToBase64Binary(String filePath) { File originalFile = new File(filePath); String encodedBase64; try { FileInputStream fileInputStreamReader = new FileInputStream(originalFile); byte[] bytes = new byte[(int)originalFile.length()]; int numBytesRead = fileInputStreamReader.read(bytes); if (numBytesRead != -1) { // Log.d(TAG, "encodeFileToBase64Binary: could not read all the file"); return null; } encodedBase64 = android.util.Base64.encodeToString(bytes, DEFAULT); return encodedBase64; } catch (IOException e) { e.printStackTrace(); return null; } }

@onuryurtturk
Copy link

@LightMan pls check your numBytesRead if condition. You're returning null if some bytes read

@Khyati1992
Copy link

Khyati1992 commented Feb 1, 2018

@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

A single line solution

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

@manishboricha
Copy link

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

@sheliyaparth
Copy link

Why not use Base64.encodeBase64String(bytes)?

@Zeriitas
Copy link

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