PDF à byte array et vice versa

j'ai besoin de convertir pdf en byte array et vice versa.

quelqu'un Peut-il m'aider?

Voici comment je suis en train de convertir en byte array

public static byte[] convertDocToByteArray(String sourcePath) {

    byte[] byteArray=null;
    try {
        InputStream inputStream = new FileInputStream(sourcePath);


        String inputStreamToString = inputStream.toString();
        byteArray = inputStreamToString.getBytes();

        inputStream.close();
    } catch (FileNotFoundException e) {
        System.out.println("File Not found"+e);
    } catch (IOException e) {
                System.out.println("IO Ex"+e);
    }
    return byteArray;
}

Si j'utilise code suivant à convertir document pdf est de se créer. Mais cela dit 'Bad Format. Not a pdf'.

public static void convertByteArrayToDoc(byte[] b) {          

    OutputStream out;
    try {       
        out = new FileOutputStream("D:/ABC_XYZ/1.pdf");
        out.close();
        System.out.println("write success");
    }catch (Exception e) {
        System.out.println(e);
    }
24
demandé sur Lahiru Ashan 2009-07-15 16:31:52

12 réponses

vous avez essentiellement besoin d'une méthode helper pour lire un flux dans la mémoire. Cela fonctionne assez bien:

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

Puis vous souhaitez appeler avec:

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

Ne pas mélanger texte et données binaires-cela ne mène qu'à des déchirures.

29
répondu Jon Skeet 2012-02-27 07:31:49

Java 7 introduit Files.readAllBytes(), qui peut lire un PDF dans un byte[] comme ceci:

import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;

Path pdfPath = Paths.get("/path/to/file.pdf");
byte[] pdf = Files.readAllBytes(pdfPath);

EDIT:

Merci Farooque de souligner: cela fonctionnera pour lire n'importe quel type de fichier, pas seulement des fichiers PDF. Tous les fichiers sont en fin de Compte juste un tas d'octets, et en tant que tel peut être lu dans un byte[].

21
répondu Chris Clark 2016-08-09 21:12:32

le problème est que vous appelez toString() sur le InputStream l'objet lui-même. Cela renvoie un String représentation de l' InputStream objet non pas le document PDF.

vous voulez lire le PDF seulement en octets car le PDF est un format binaire. Vous pourrez alors écrire la même chose byte array et il sera valide PDF comme il n'a pas été modifié.

par exemple, pour lire un fichier en octets

File file = new File(sourcePath);
InputStream inputStream = new FileInputStream(file); 
byte[] bytes = new byte[file.length()];
inputStream.read(bytes);
10
répondu Mark 2014-06-25 08:38:20

Vous pouvez le faire en utilisant Apache Commons IO sans se soucier des détails internes.

Utiliser org.apache.commons.io.FileUtils.readFileToByteArray(File file) qui renvoient des données de type byte[].

Cliquez ici pour Javadoc

5
répondu Narendra 2014-06-25 08:29:32

n'êtes-vous pas en train de créer le fichier pdf mais pas en train de réécrire le tableau byte? Par conséquent, vous ne pouvez pas ouvrir le PDF.

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

ceci s'ajoute à la lecture correcte dans le tableau PDF to byte.

1
répondu David 2009-07-15 12:45:37

appel toString() sur un InputStream ne fait pas ce que vous pensez qu'il fait. Même si C'était le cas, un PDF contient des données binaires, donc vous ne voudriez pas le convertir en chaîne d'abord.

Ce que vous devez faire est de lire le flux, à écrire les résultats dans un ByteArrayOutputStream, puis convertir le ByteArrayOutputStream en byte tableau en appelant 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
répondu Eric Petroelje 2014-06-25 08:29:25
public static void main(String[] args) throws FileNotFoundException, IOException {
        File file = new File("java.pdf");

        FileInputStream fis = new FileInputStream(file);
        //System.out.println(file.exists() + "!!");
        //InputStream in = resource.openStream();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        try {
            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                bos.write(buf, 0, readNum); //no doubt here is 0
                //Writes len bytes from the specified byte array starting at offset off to this byte array output stream.
                System.out.println("read " + readNum + " bytes,");
            }
        } catch (IOException ex) {
            Logger.getLogger(genJpeg.class.getName()).log(Level.SEVERE, null, ex);
        }
        byte[] bytes = bos.toByteArray();

        //below is the different part
        File someFile = new File("java2.pdf");
        FileOutputStream fos = new FileOutputStream(someFile);
        fos.write(bytes);
        fos.flush();
        fos.close();
    }
1
répondu Sami Youssef 2015-08-16 19:17:42

Cela fonctionne pour moi:

try(InputStream pdfin = new FileInputStream("input.pdf");OutputStream pdfout = new FileOutputStream("output.pdf")){
    byte[] buffer = new byte[1024];
    int bytesRead;
    while((bytesRead = pdfin.read(buffer))!=-1){
        pdfout.write(buffer,0,bytesRead);
    }
}

mais la réponse de Jon ne fonctionne pas pour moi si elle est utilisée de la manière suivante:

try(InputStream pdfin = new FileInputStream("input.pdf");OutputStream pdfout = new FileOutputStream("output.pdf")){

    int k = readFully(pdfin).length;
    System.out.println(k);
}

sorties zéro comme longueur. Pourquoi est-ce ?

0
répondu Sridhar 2012-04-29 17:59:43

aucun de ceux-ci n'a fonctionné pour nous, probablement parce que notre inputstreambyte s d'un appel de repos, et non d'un fichier pdf hébergé localement. Ce qui a fonctionné était d'utiliser RestAssured pour lire le PDF comme un flux d'entrée, puis en utilisant Tika pdf reader pour l'analyser et ensuite appeler le toString() méthode.

import com.jayway.restassured.RestAssured;
import com.jayway.restassured.response.Response;
import com.jayway.restassured.response.ResponseBody;

import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.sax.BodyContentHandler;
import org.apache.tika.parser.Parser;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;

            InputStream stream = response.asInputStream();
            Parser parser = new AutoDetectParser(); // Should auto-detect!
            ContentHandler handler = new BodyContentHandler();
            Metadata metadata = new Metadata();
            ParseContext context = new ParseContext();

            try {
                parser.parse(stream, handler, metadata, context);
            } finally {
                stream.close();
            }
            for (int i = 0; i < metadata.names().length; i++) {
                String item = metadata.names()[i];
                System.out.println(item + " -- " + metadata.get(item));
            }

            System.out.println("!!Printing pdf content: \n" +handler.toString());
            System.out.println("content type: " + metadata.get(Metadata.CONTENT_TYPE));
0
répondu gorbysbm 2014-06-25 09:45:15

pour convertir pdf en byteArray :

public byte[] pdfToByte(String filePath)throws JRException {

         File file = new File(<filePath>);
         FileInputStream fileInputStream;
         byte[] data = null;
         byte[] finalData = null;
         ByteArrayOutputStream byteArrayOutputStream = null;

         try {
            fileInputStream = new FileInputStream(file);
            data = new byte[(int)file.length()];
            finalData = new byte[(int)file.length()];
            byteArrayOutputStream = new ByteArrayOutputStream();

            fileInputStream.read(data);
            byteArrayOutputStream.write(data);
            finalData = byteArrayOutputStream.toByteArray();

            fileInputStream.close(); 

        } catch (FileNotFoundException e) {
            LOGGER.info("File not found" + e);
        } catch (IOException e) {
            LOGGER.info("IO exception" + e);
        }

        return finalData;

    }
0
répondu Riddhi Gohil 2016-04-26 09:17:17

j'ai mis en place un comportement similaire dans mon Application aussi sans faute. Voici ma version de code, et il est fonctionnel.

    byte[] getFileInBytes(String filename) {
    File file  = new File(filename);
    int length = (int)file.length();
    byte[] bytes = new byte[length];
    try {
        BufferedInputStream reader = new BufferedInputStream(new 
    FileInputStream(file));
    reader.read(bytes, 0, length);
    System.out.println(reader);
    // setFile(bytes);

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return bytes;
    }
0
répondu Akash Roy 2018-05-31 07:51:39

les fichiers PDF peuvent contenir des données binaires et il y a de fortes chances qu'elles soient altérées lorsque vous faites du ToString. Il me semble que vous voulez ceci:

        FileInputStream inputStream = new FileInputStream(sourcePath);

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

        inputStream .read(bytearray);
-2
répondu plinth 2009-07-15 12:35:49