SoFunction
Updated on 2025-03-08

How to convert strings and byte arrays into input streams

Convert strings and byte arrays into input streams

Convert a string to an input stream:

String str = "budaye";
ByteArrayInputStream in = new ByteArrayInputStream(("UTF-8"));

ByteArrayInputStream is a byte array input stream that inherits from InputStream.

It contains an internal buffer that contains bytes read from the stream.

If we want to convert a string or byte array into a character stream, we can use the ByteArrayInputStream class.

Input stream, output stream, file, byte array, Base64 string conversion

Convert input streams into byte arrays

Get the input stream through my encapsulated download service and then use Go to get the byte array

InputStream inputStream = (tenantId, .BUCKET_NAME_CAN, ());
                                byte[] imgByte = (inputStream);

Note that the stream can only be used once, and the stream needs to be closed after using up.

Convert input stream to base64 encoded string

We need to convert to byte array first and then convert string

  • Another solution to convert byte arrays
  public static byte[] readInputStream(InputStream is) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length = 0;
        try {
            while ((length = (buffer)) != -1) {
                (buffer, 0, length);
            }
            ();
        } catch (IOException e) {
            ("IOException", e);
        }
        byte[] data = ();
        try {
            ();
            ();
        } catch (IOException e) {
            ("IOException", e);
        }
        return data;
    }
  • Convert byte array to Base64 string
imageFile = (data);

Convert input stream to file

  //Data flow to MultipartFile file                                MultipartFile multipartFile = new MockMultipartFile("file", "file" +"."+ fileType, fileType, inputStream);
                                ResponseEntity<ResponseCommonDTO> recognizeResult = (tenantId, companyCode, employeeNumber, multipartFile);

Convert local files to input streams

String path = "C:\\Users\\mai\\Desktop\\Invoice Test Collection\\";
File file = new File(path);
InputStream ins = new FileInputStream(file);

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.