java-file Transcoding method

Source: Internet
Author: User

http://blog.csdn.net/zhengqiqiqinqin/article/details/12621201

Law One: java.lang.string

    //Law One: XX code-->new String (byte[]b,charset xx)-->stirng.getbytes (Charset yy)-->yy encoding     Public Static voidMethod_1 ()throwsException {fileinputstream fis=NewFileInputStream ("F:\\test\\test.txt"); File F=NewFile ("F:\\test\\copy-test2.txt"); if(!f.exists ()) f.createnewfile (); FileOutputStream Fos=NewFileOutputStream (f); byte[] b=New byte[10]; intLen=0;  while((Len=fis.read (b))!=-1)        {                 //idea: GB2312 to UTF-8, must pass an intermediate encoding medium, here is a string//converts a byte array to a string (its encoding is GBK as the operating system)//The string is then converted to another encoded byte arrayString s=NewString (B,0,len, "GB2312"); b=s.getbytes ("UTF-8"); //Fos.write (B,0,len); Note: This is wrong because the length of the byte array after transcoding has changed, not the original length of the byte arrayFos.write (b); }         if(fos!=NULL) Fos.close (); if(fis!=NULL) Fis.close (); }

Law II: java.io.inputstreamreader/outputstreamwriter: Bridge Conversion

//Law II (recommended): "IO Stream" XX code-->inputstreamreader (file, "XX")--->outputstreamwriter (file, "yy")-->yy encoding     Public Static voidMethod_2 ()throwsException {fileinputstream fis=NewFileInputStream ("F:\\test\\test.txt"); File F=NewFile ("F:\\test\\copy-test.txt"); if(!f.exists ()) f.createnewfile (); FileOutputStream Fos=NewFileOutputStream (f); //IO Transfer ConnectionInputStreamReader isr=NewInputStreamReader (FIS, "GB2312"); OutputStreamWriter OSW=NewOutputStreamWriter (FOS, "UTF-8"); //read:         Char[] cs=New Char[1024]; intLen=0;  while((Len=isr.read (CS))!=-1) {Osw.write (CS,0, Len); }         //Close the streamOsw.flush ();        Osw.close ();    Isr.close (); }

Method Three: Java.nio.Charset

java-file Transcoding method

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.