java convert inputStream to base64 string

前端 未结 4 612
说谎
说谎 2021-02-07 01:47

There is a way to convert inputStream to a String, and encode it to base64, right? In my function, I get InputStream param, and need to insert it into the BLOB field in my Oracl

4条回答
  •  心在旅途
    2021-02-07 02:32

    The simplest way would be to use IOUtils from apache-commons to do that:

    String result= IOUtils.toString(inputStream, ENCODING); 
    

    From the documentation:

    toString(byte[] input, String encoding) Gets the contents of a byte[] as a String using the specified character encoding.

    After that To Encode/Decode in Base64:

    // Encode 
    String resultBase64Encoded = Base64.getEncoder().encodeToString(result.getBytes("utf-8"));
    
    
    // Decode
    byte[] asBytes = Base64.getDecoder().decode(resultBase64Encoded);
    String resultAsStringAgain= String(asBytes, "utf-8")
    

    Note: I'm assuming you use JDK 8 for the Encode/Decode part.

    Apparently the OP wants just to persist an InputStream to the DB. You can do that directly using JDBC:

    InputStream inputStream = ......;
    String sql = "INSERT INTO TABLE_NAME(COLUMN_NAME) values (?)";
    PreparedStatement statement = connection.prepareStatement(sql);
    statement.setBlob(1, inputStream);
    statement.executeUpdate();
    

提交回复
热议问题