Article/bael 5516 how to convert input stream to base64 string (#12219)

* java-shallow-deep tutorial

* BAEL-5516 How to Convert InputStream to base64 String
 - Junit test demonstrating the code

* BAEL-5516 - How-to-Convert-InputStream-to-base64-String
Cleaned up files

* BAEL-5516 - How-to-Convert-InputStream-to-base64-String
 - updated per Jira comments

* BAEL-5516 - How-to-Convert-InputStream-to-base64-String
 - rename and formatting to match Baeldung standards
This commit is contained in:
Christopher C. Smith 2022-06-30 00:01:55 -04:00 committed by GitHub
parent 31732540b4
commit 103a374ba1
2 changed files with 49 additions and 0 deletions

View File

@ -0,0 +1,49 @@
package com.baeldung.inputstreamtobase64;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.InputStream;
import java.util.Base64;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
/**
* Test the Stream to base64 conversion
*/
public class InputStreamToBase64UnitTest {
/**
* Test stream to base64 conversion
* @throws Exception
*/
@Test
public void givenABinaryInputStream_whenItIsConvertedToBase64_thenItCanBeDecoded() throws Exception {
// given a binary input stream
InputStream sourceStream = getClass().getClassLoader().getResourceAsStream("logo.png");
byte[] sourceBytes = IOUtils.toByteArray(sourceStream);
// when it is converted to base64
String encodedString = Base64.getEncoder().encodeToString(sourceBytes);
assertNotNull(encodedString);
// then it can be decoded
byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
assertNotNull(decodedBytes);
assertTrue(decodedBytes.length == sourceBytes.length);
assertTrue(calculateChecksum(decodedBytes) == calculateChecksum(sourceBytes));
}
/**
* Calculate a checksum
* @param bytes array of bytes to check
* @return the total sum of all bytes
*/
private int calculateChecksum(byte[] bytes) {
int checksum = 0;
for(int index=0; index < bytes.length; index++) {
checksum+=bytes[index];
}
return checksum;
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB