PDF к массиву байтов и наоборот

Поскольку Kent Beck отмечает при обсуждении защитных пунктов в Шаблоны Реализации создание стандартной программы иметь однократную и точку выхода...

"должен был предотвратить беспорядок, возможный при вскакивании и из многих местоположений в той же стандартной программе. Это проявило здравый смысл, когда относился к ФОРТРАНУ или программам на языке ассемблера, записанным с большим количеством глобальных данных, где даже понимание, какие операторы выполнялись, было тяжелой работой... с маленькими методами и главным образом локальными данными, это напрасно консервативно".

я нахожу функцию записанной с защитными пунктами намного легче следовать, чем один длинный вложенный набор if then else операторы.

27
задан Lahiru Ashan 28 November 2016 в 10:52
поделиться

5 ответов

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.

32
ответ дан 28 November 2019 в 04:21
поделиться

The problem is that you are calling toString() on the InputStream object itself. This will return a String representation of the InputStream object not the actual PDF document.

You want to read the PDF only as bytes as PDF is a binary format. You will then be able to write out that same byte array and it will be a valid PDF as it has not been modified.

e.g. to read a file as bytes

File file = new File(sourcePath);
InputStream inputStream = new FileInputStream(file); 
byte[] bytes = new byte[file.length()];
inputStream.read(bytes);
11
ответ дан 28 November 2019 в 04:21
поделиться

Are'nt you creating the pdf file but not actually writing the byte array back? Therefore you cannot open the PDF.

out = new FileOutputStream("D:/ABC_XYZ/1.pdf");
out.Write(b, 0, b.Length);
out.Position = 0;
out.Close();

This is in addition to correctly reading in the PDF to byte array.

1
ответ дан 28 November 2019 в 04:21
поделиться

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();
1
ответ дан 28 November 2019 в 04:21
поделиться

PDFs may contain binary data and chances are it's getting mangled when you do ToString. It seems to me that you want this:

        FileInputStream inputStream = new FileInputStream(sourcePath);

        int numberBytes = inputStream .available();
        byte bytearray[] = new byte[numberBytes];

        inputStream .read(bytearray);
-2
ответ дан 28 November 2019 в 04:21
поделиться
Другие вопросы по тегам:

Похожие вопросы: