byte[]数组存储到文件中

本文详细介绍了在Android应用中如何使用byte数组存储文件的具体步骤,包括在清单文件中配置读写权限,以及通过代码实现文件的写入过程。文中提供了具体的代码示例,展示了如何创建文件、写入数据并确保数据正确保存。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先在清单文件中写入读写权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
然后写代码:

/**
 * byte数组存储文件
 * @param bs
 * @throws IOException
 */
public void writeBytesToFile(byte[] bs) throws IOException {
   OutputStream out = new FileOutputStream(getDatasFilePath(this) + "mydatas.txt" );
   InputStream is = new ByteArrayInputStream(bs);
   byte[] buff = new byte[1024];
   int len;
   while ((len = is.read(buff)) != -1) {
      out.write(buff, 0, len);
   }
   is.close();
   out.close();
}

/**
 * 获取文件夹路径
 *
 * @param context
 * @return
 */
private static String getDatasFilePath(Context context) {
   String path = null;
   try {
      path = Environment.getExternalStorageDirectory().getCanonicalPath() + "/"
            + context.getResources().getString(R.string.app_name) + "/demo/";
      File file = new File(path);
      if (!file.exists()) {
         file.mkdirs();
      }
   } catch (IOException e) {
      e.printStackTrace();
   }
   Log.e("TAG", "getDatasFilePath: " + path);
   return path;
}

调用的时候:

try {
   writeBytesToFile(content);
} catch (IOException e) {
   e.printStackTrace();
}

完事,就是这么简单!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值