2016-11-30 6 views
-1

J'essaie (en Java) d'obtenir un document de fichier puis de le convertir en bitArray par la suite en une chaîne de représentation similaire, puis de nouveau au tableau de bits d'origine et enfin le document final original.Convertir le fichier en tableau d'octets puis en chaîne puis en tableau d'octets puis au fichier d'origine

Voici mon code, Mais le fichier généré n'est pas visible dans ce cas l'image.

try { 
     File file = new File("C:/Users/dkimigho/Downloads/kenyapowerlogo.jpg"); 

     FileInputStream fis = null; 
     try { 
      fis = new FileInputStream(file); 
     } catch (FileNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     //create FileInputStream which obtains input bytes from a file in a file system 
     //FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader. 

     ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
     byte[] buf = new byte[1024]; 
     try { 
      for (int readNum; (readNum = fis.read(buf)) != -1;) { 
       //Writes to this byte array output stream 
       bos.write(buf, 0, readNum); 
       System.out.println("read " + readNum + " bytes,"); 
      } 
     } catch (IOException ex) { 
      Logger.getLogger(ARRAYBITStoPDF.class.getName()).log(Level.SEVERE, null, ex); 
     } 

     byte[] bytes = bos.toByteArray(); 

     System.out.println("byte1"); 
     for (int i = 0; i < bytes.length; i++) { 
      System.out.print(bytes[i]); 
     } 
     //We have the bytes now convert to String 
     String stringbytearray=new String(bytes); 

     System.out.println("stringbytearray: "+stringbytearray); 

     //We have the bytes now convert to String 

     byte[] content = stringbytearray.getBytes(); 
     System.out.println("byte2"); 
     for (int i = 0; i < content.length; i++) { 
      System.out.print(content[i]); 
     } 

     int size = bytes.length; 
     InputStream isfilecontent = null; 
     byte[] b = new byte[size]; 
     isfilecontent = new ByteArrayInputStream(content); 

     //writing the downloaded data into a PDF file 
     FileOutputStream fileOutputpdf = new FileOutputStream("C:/Users/dkimigho/Downloads/mykenyapowerlogo.jpg"); 

     /* use binary I/O to prevent line based operation messing with the encoding.*/ 
     byte[] buf2 = new byte[2048]; 
     int b_read = 0; 
     while ((b_read = isfilecontent.read(buf2)) > 0) { 
      fileOutputpdf.write(buf2, 0, b_read); 
     } 
     fileOutputpdf.flush(); 
     //closed the output stream 
     fileOutputpdf.close(); 

    } catch (IOException e) { 
     // handle IOException 
     System.out.println(e.getMessage()); 
    } 

Toute aide sur ce que je fais mal? Une correction de mon code à un code fonctionnel peut être importante.

+0

Une aide indiquant ce qui ne fonctionne pas? Vous devriez avoir sur la méthode par fonctionnalité. Ce serait plus facile de tester ce qui fonctionne, et ce qui ne fonctionne pas. Et vous devriez commencer avec un simple fichier texte ... un jpg est plus complexe pour vérifier la valeur étape par étape. – AxelH

+0

Java doc: 'String (octets [] octets) Construit une nouvelle chaîne en décodant ** le tableau d'octets spécifié ** en utilisant le jeu de caractères par défaut de la plateforme **. Je pense que cela modifie votre contenu – Fefux

+1

Conversion d'octets en chaîne les corrompt/les modifie. Vous pouvez stocker des octets dans une chaîne en C, mais vous ne pouvez pas le faire en Java. En Java, vous stockez des octets dans un tableau d'octets ou [ByteBuffer] (http://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html). N'utilisez pas de chaînes du tout ici. – VGR

Répondre

0

J'ai trouvé une réponse que l'on doit utiliser JAVA 8 java.util.Base64 pour encoder et décoder les octets sans perdre d'informations sur le document. J'espère que ce sera utile à quelqu'un.

/* 
    * 1. How to convert an image file to byte array? 
    */ 
    try { 
     File file = new File("C:/Users/qwerty/Downloads/factura.pdf"); 

     FileInputStream fis = null; 
     try { 
      fis = new FileInputStream(file); 
     } catch (FileNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     //create FileInputStream which obtains input bytes from a file in a file system 
     //FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader. 

     ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
     byte[] buf = new byte[1024]; 
     try { 
      for (int readNum; (readNum = fis.read(buf)) != -1;) { 
       //Writes to this byte array output stream 
       bos.write(buf, 0, readNum); 
       // System.out.println("read " + readNum + " bytes,"); 
      } 
     } catch (IOException ex) { 
      Logger.getLogger(ARRAYBITStoPDF.class.getName()).log(Level.SEVERE, null, ex); 
     } 

     byte[] bytes = bos.toByteArray(); 
     bos.close(); // should be inside a finally block 
     //We have the bytes now convert to String 

     // ENCODING 
     String encodedDoc= Base64.getEncoder().encodeToString(bytes); 

     System.out.println(encodedDoc); 

     // DECODING 
     int size = bytes.length; 
     InputStream isfilecontent = null; 
     //byte[] b = new byte[size]; 
     isfilecontent = new ByteArrayInputStream(Base64.getDecoder().decode(encodedDoc)); 

     //writing the downloaded data into a PDF file 
     FileOutputStream fileOutputpdf = new FileOutputStream("C:/Users/qwerty/Downloads/myfactura.pdf"); 

     /* use binary I/O to prevent line based operation messing with the encoding.*/ 
     byte[] buf2 = new byte[2048]; 
     int b_read = 0; 
     while ((b_read = isfilecontent.read(buf2)) > 0) { 
      fileOutputpdf.write(buf2, 0, b_read); 
     } 
     fileOutputpdf.flush(); 
     //closed the output stream 
     fileOutputpdf.close(); 

    } catch (IOException e) { 
     // handle IOException 
     System.out.println(e.getMessage()); 
    }