繁体   English   中英

Android将字节数组转换为文件并保存在SD卡中的文件

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

我在服务器中的字节数组中转换一个文件,并通过json字符串发送到Android客户端..通过此代码我转换该文件:

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();
        }

在Android客户端我得到的值如下:“SGVsbG8gRG93bmxvYWQgaXMgd29ya2luZw ==”(字符串类型)

那么我如何将此代码转换为字节并转换为文件并保存在SD卡中?

您有使用BASE64编码编码的二进制数据。

要解码它,您可以使用android.util.Base64类

要了解如何将文件写入外部存储,请阅读本文

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();
        }
    });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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