Convert android files to base64 and Base64 files

Source: Internet
Author: User

File Transfer is required in the project. The best way to facilitate transmission is to convert the file into a base64 string, and then convert the base64 string into a byte stream and save it in the file. However, this method is simple, but it still needs to be selected based on actual needs. The disadvantage is that it cannot be converted into too many files. Too many files will cause efficiency problems. I did not do any in-depth research or practical tests. If you are interested, you can perform in-depth research and testing on your own.
Import android. util. Base64 ;/**
* EncodeBase64File: (convert the object to a base64 string ).

* @ Author guhaizhou@126.com
* @ Param path: file path
* @ Return
* @ Throws Exception
* @ Since JDK 1.6
*/
Public static String encodeBase64File (String path) throws Exception {
File file = new File (path );
FileInputStream inputFile = new FileInputStream (file );
Byte [] buffer = new byte [(int) file. length ()];
InputFile. read (buffer );
InputFile. close ();
Return Base64.encodeToString (buffer, Base64.DEFAULT );
}

/**
* DecoderBase64File: (decodes base64 characters to save the file ).

* @ Author guhaizhou@126.com
* @ Param base64Code: encoded string
* @ Param savePath: file storage path
* @ Throws Exception
* @ Since JDK 1.6
*/
Public static void decoderBase64File (String base64Code, String savePath) throws Exception {
// Byte [] buffer = new BASE64Decoder (). decodeBuffer (base64Code );
Byte [] buffer = Base64.decode (base64Code, Base64.DEFAULT );
FileOutputStream out = new FileOutputStream (savePath );
Out. write (buffer );
Out. close ();

}


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.