且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PDF到字节数组,反之亦然

更新时间:2022-12-07 17:06:58

你基本上需要一个辅助方法将流读入内存。这很好用:

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();
}

然后你打电话给:

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.