首先在清單文件中寫入讀寫權限
<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(); }
完事,就是這麼簡單!