PDF to byte array and vice versa

前端 未结 13 1211
独厮守ぢ
独厮守ぢ 2020-11-27 04:19

I need to convert pdf to byte array and vice versa.

Can any one help me?

This is how I am converting to byte array

public static byte[] conve         


        
13条回答
  •  清酒与你
    2020-11-27 04:43

    Calling toString() on an InputStream doesn't do what you think it does. Even if it did, a PDF contains binary data, so you wouldn't want to convert it to a string first.

    What you need to do is read from the stream, write the results into a ByteArrayOutputStream, then convert the ByteArrayOutputStream into an actual byte array by calling toByteArray():

    InputStream inputStream = new FileInputStream(sourcePath);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    
    int data;
    while( (data = inputStream.read()) >= 0 ) {
        outputStream.write(data);
    }
    
    inputStream.close();
    return outputStream.toByteArray();
    

提交回复
热议问题