Java byte array and string conversion issues

Source: Internet
Author: User

Today, when you use the byte stream to copy a picture, there is a problem, that is, when you convert an array of bytes to a string, there is a different length. This is actually a wrong operation.

 public static void Main (string[] args) throws IOException {//First way (no problem)/*fileinputstream FIS = new fileinputs    Tream ("d:\\ belle. jpg");    FileOutputStream fos = new FileOutputStream ("f:\\ccc\\ belle. jpg");    int Len;    while (len = Fis.read ())! =-1) {fos.write (len);    } fos.close ();    Fis.close (); *///The second way, there will be a problem/*fileinputstream FIS = new FileInputStream ("d:\\ belle. jpg");    byte[] arr = new byte[1024 * 6];    int Len;    StringBuilder sb = new StringBuilder ();    while (len = Fis.read (arr))! =-1) {Sb.append (new String (Arr,0,len));    } fileoutputstream fos = new FileOutputStream ("f:\\ccc\\ belle. jpg");    Fos.write (Sb.tostring (). GetBytes ());    Fos.close ();            Fis.close (); *///Third way to solve the problem fileinputstream FIS = new FileInputStream ("d:\\ belle. jpg");    byte[] arr = new byte[1024 * 6];    int Len;    StringBuilder sb = new StringBuilder ();    while (len = Fis.read (arr))! =-1) {Sb.append (new String (Arr,0,len, "iso-8859-1"));  }  FileOutputStream fos = new FileOutputStream ("f:\\ccc\\ belle. jpg");    Fos.write (Sb.tostring (). GetBytes ("iso-8859-1"));    Fos.close (); Fis.close ();}

The reason for this is that when you use a character array to read a picture and convert it to a string type, it is converted using the editor's default encoding, but the default encoding method (UTF-8 or other)
Garbled (the reason is that multiple bytes into characters when the Code table does not know, will appear?), so the length will increase a lot. And when using iso-8859-1, it is a byte-by-byte conversion, the following write
Time to specify the encoding, which is equivalent to a reversal, so no problem occurred

Java byte array and string conversion issues

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.