【问题标题】:Android Convert bytes array to File and Save file in SD cardAndroid将字节数组转换为文件并将文件保存在SD卡中
【发布时间】:2013-06-17 13:50:25
【问题描述】:

我在服务器中将一个文件转换为字节数组,并以 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卡中?

【问题讨论】:

标签: java android json android-intent


【解决方案1】:

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

要对其进行解码,您可以使用android.util.Base64 class

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

【讨论】:

    【解决方案2】:
    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();
            }
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-04
      • 1970-01-01
      • 2014-11-05
      相关资源
      最近更新 更多