简体   繁体   中英

Android Convert bytes array to File and Save file in SD card

I convert one file in byte array in server and send as a by json string to Android Client.. by this code i convert that file :

FileInputStream fileInputStream=null;

        File file = new File("C:\\testing.txt");

        byte[] bFile = new byte[(int) file.length()];

        try {
            //convert file into array of bytes
        fileInputStream = new FileInputStream(file);
        fileInputStream.read(bFile);
        fileInputStream.close();
}catch(Exception e){
            e.printStackTrace();
        }

and in Android Client i got the value like : "SGVsbG8gRG93bmxvYWQgaXMgd29ya2luZw==" (In String Type)

So how i convert this code into byte and convert in file and save in sd card?

You have binary data encoded using BASE64 encoding.

To decode it you can use android.util.Base64 class .

To learn how to write file to an external store read this article .

try {
     /* file_byte is yous json string*/
    byte[] decodestring = Base64.decode(file_byte, Base64.DEFAULT);
    File file = Environment.getExternalStorageDirectory();
    File dir = new File(file.getAbsolutePath() + "/VPM/Document/");
     if (!dir.exists()) {
         dir.mkdirs();
     }
     File document = new File(dir, doc_name);

     if (document.exists()) {
         document.delete();
      }

     FileOutputStream fos = new FileOutputStream(document.getPath());
      fos.write(decodestring);
      fos.close();
   } catch (Exception e) {
    Log.e(TAG, "error: " + e.getMessage());
    runOnUiThread(new Runnable() {
    @Override
        public void run() {
            Snackbar.make(root_doc, "Failed to download file..", Snackbar.LENGTH_LONG)
            .setAction("Action", null).show();
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM