Search code examples
javastringbase64inputstream

Convert InputStream to base64 string


There is a way to convert an InputStream to a String, and encode it to base64, right?

In my function, I get InputStream parameter, and need to insert it into the BLOB field in my Oracle database table.

Is there a way to do that?

(My database object contains string field to save the image, but I don't find any way to convert the InputStream to string in base 64 format.)


Solution

  • In case someone is looking for solution without external libraries. Java8 adds Base64 utility class which contains getEncoder() method. Java9 adds fancy method on InputStream called readAllBytes() Link to api

    So now you without any external libraries your code may look like

    import java.io.InputStream;
    import java.util.Base64;
    
    public String encode(InputStream stream) throws IOException {
      final var bytes = stream.readAllBytes();
    
      return Base64.getEncoder().encodeToString(bytes);
    }