首先在清单文件中写入读写权限
<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();
}
完事,就是这么简单!
本文详细介绍了在Android应用中如何使用byte数组存储文件的具体步骤,包括在清单文件中配置读写权限,以及通过代码实现文件的写入过程。文中提供了具体的代码示例,展示了如何创建文件、写入数据并确保数据正确保存。
924

被折叠的 条评论
为什么被折叠?



