PDF to byte array and vice versa

前端 未结 13 1250
独厮守ぢ
独厮守ぢ 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:42

    You basically need a helper method to read a stream into memory. This works pretty well:

    public static byte[] readFully(InputStream stream) throws IOException
    {
        byte[] buffer = new byte[8192];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
    
        int bytesRead;
        while ((bytesRead = stream.read(buffer)) != -1)
        {
            baos.write(buffer, 0, bytesRead);
        }
        return baos.toByteArray();
    }
    

    Then you'd call it with:

    public static byte[] loadFile(String sourcePath) throws IOException
    {
        InputStream inputStream = null;
        try 
        {
            inputStream = new FileInputStream(sourcePath);
            return readFully(inputStream);
        } 
        finally
        {
            if (inputStream != null)
            {
                inputStream.close();
            }
        }
    }
    

    Don't mix up text and binary data - it only leads to tears.

提交回复
热议问题