3

I have following byte[] which comes from database.

0x255044462D312E330A25AAABAC

Note: above byte array is sample full file is not here because of length.

UPDATE:

But I am getting like [B@7ffd10fa format


  • Before you see code please read here:

When I send bytes which returns getPdfByteStream() method it sends attachment in email like original file. But when I get from database and send it sends corrupted file.


UPDATE:

Entity.class

@Lob
@Column(name = "ATTACHED_FILE")
private byte[] attachedFile;

//getter()/setter();

Code which sends email

 try {
        MimeBodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setText(content);

       //byte[] bytes = getPDFByteStream(); //Returns byte[] reading local drive file


         **UPDATE:**

        //bytes[] bytes=entity.getAttachedFile(); // It gets value from entity.

        /**
        ** It is getting like "[B@7ffd10fa" format but m storing on database like "0x255044462D312E330A25" format
        **/

        String string="0x255044462D312E330A25";
        byte[] bytes =string.getBytes(Charset.forName("UTF-8"));
        System.out.println("bytes " + bytes.toString());

        DataSource dataSource = new ByteArrayDataSource(bytes, "application/pdf");
        MimeBodyPart pdfBodyPart = new MimeBodyPart();
        pdfBodyPart.setDataHandler(new DataHandler(dataSource));
        pdfBodyPart.setFileName("bankAdminReport.pdf");

        MimeMultipart mimeMultipart = new MimeMultipart();
        mimeMultipart.addBodyPart(textBodyPart);
        mimeMultipart.addBodyPart(pdfBodyPart);

        InternetAddress iaSender = new InternetAddress(sender);
        InternetAddress iaRecipient = new InternetAddress(recipient);

        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setSender(iaSender);
        mimeMessage.setSubject(subject);
        mimeMessage.setRecipient(Message.RecipientType.TO, iaRecipient);
        mimeMessage.setContent(mimeMultipart);

        Transport.send(mimeMessage);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

getPDFByteStream() method

public static byte[] getPDFByteStream() throws IOException {
    File file = new File("C:\\pdf\\bankAdminReport.pdf");

    byte[] b = new byte[(int) file.length()];
    try {
        FileInputStream fileInputStream = new FileInputStream(file);
        fileInputStream.read(b);
    } catch (FileNotFoundException e) {
        System.out.println("File Not Found.");
        e.printStackTrace();
    } catch (IOException e1) {
        System.out.println("Error Reading The File.");
        e1.printStackTrace();
    }
    return b;
}

Can anyone guide me.

The main problem is when I send file reading from local drive it sends perfectly. but if I send getting from database or any local variable file corrupts.

Please comment below if you have any query regarding question. Thanks.

Yubaraj
  • 3,800
  • 7
  • 39
  • 57
  • 1
    string.getBytes(Charset.forName("UTF-8")); looks for me wrong - I test it later – OkieOth Jun 03 '14 at 09:51
  • Thanks @OkieOth I saw this http://stackoverflow.com/questions/18571223/convert-java-string-to-byte-array . You can also take reference. – Yubaraj Jun 03 '14 at 09:58
  • silly idea, but shouldn't the "0x"-prefix be removed from your string? – injecteer Jun 03 '14 at 10:10
  • Do you mean `255044462D312E330A25` instead of `0x255044462D312E330A25` ?. @injecteer – Yubaraj Jun 03 '14 at 10:11
  • What database type has your column that holds the PDF? – OkieOth Jun 03 '14 at 10:33
  • I have entity which holds value as `byte[]` and m using SQL database as `varbinary(max)` column type – Yubaraj Jun 03 '14 at 10:37
  • Try at first that your can serialisation and deserialisation the same byte array like your getPDFByteStream function. – OkieOth Jun 03 '14 at 11:20
  • 1
    Can you do an `Arrays.equals(bytesFromDb, bytesFromPdf)` just to make sure that you actually get the same byte array from the database and from the PDF? Also, use `Arrays.toString(bytesFromDb)` and `Arrays.toString(bytesFromPdf)` to compare them manually. – Zoltán Jun 03 '14 at 13:04
  • Please add the resulting eml file to the question, so that we can see how the email looks after you added the PDF. – tquadrat Aug 29 '23 at 09:12

2 Answers2

0

This

byte[] bytes="0x255044462D312E330A25AAABAC".getBytes();

will also encode the leading "0x". Furthermore, it seems that you are trying to convert from hexadecimal values to a byte array, whereas this method would convert the character values to bytes.

I believe what you are looking for is

byte[] bytes = java.xml.bind.DatatypeConverter.parseHexBinary("255044462D312E330A25AAABAC");

Try that.

Zoltán
  • 21,321
  • 14
  • 93
  • 134
  • I got exception: `java.lang.IllegalArgumentException: hexBinary needs to be even-length: `. It has not even length – Yubaraj Jun 03 '14 at 10:42
  • Try appending a zero to the beginning. Could you show the code you use to fetch the data from the database? Are you sure you can't just get it as a byte array already instead of a string and then converting it back? – Zoltán Jun 03 '14 at 10:46
0

Imo, it's a problem of String conversion ... The following example illustrates a way - maybe not the smartest :-D

public class TestString2Binary {
    public static void main(String[] args) {
        String testText="This is \n a sample";
        System.out.println("String.toString(): ");
        System.out.println(testText);
        byte[] b=testText.getBytes();
        System.out.println("byte[]-toString(): ");
        System.out.println(b);

        System.out.println("byte[] values - toString(): ");
        for (byte x:b) {
            if (x<100)
                System.out.print("0"+x);
            else
                System.out.print(x);
        }

        String s="084104105115032105115032010032097032115097109112108101";
        System.out.println("imo the back converting to String goes wrong:");
        System.out.println(s.getBytes());
        System.out.println(new String(s.getBytes()));
        System.out.println(s.getBytes(Charset.forName("UTF-8")));
        System.out.println(new String(s.getBytes(Charset.forName("UTF-8"))));

        int recoveredBLength=s.length()/3;
        byte[] recoveredB=new byte[recoveredBLength];
        for (int i=0;i<recoveredBLength;i++) {
            String part=s.substring(i*3,(i*3)+3);
            recoveredB[i]=Byte.parseByte(part);
        }

        System.out.println("the original string: ");
        System.out.println(new String(recoveredB));


    }
}
OkieOth
  • 3,604
  • 1
  • 19
  • 29