首先在清单文件中写入读写权限
<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(); }
完事,就是这么简单!