Android 文件读写 + 申请权限

编程入门 行业动态 更新时间:2024-10-21 16:36:13

Android 文件读写 + 申请<a href=https://www.elefans.com/category/jswz/34/1771295.html style=权限"/>

Android 文件读写 + 申请权限

/***  获取文件*  /storage/emulated/0/xxx/xxx.text*  /data/xxx/xxx.text* @return*/private static File getFile() {File file = null;//SD卡存在if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {file = Environment.getExternalStorageDirectory();} else {file = Environment.getDataDirectory();}file = new File(file.getPath() + BASE_URL);if (!file.exists()) {file.mkdir();}file = new File(file.getPath() + FILE_NAME);Log.d(TAG, "getFile: " + file.getPath());return file;}/*** 写入内容* @param content*/public static void write(String content) {BufferedWriter writer = null;FileOutputStream out = null;try {out = new FileOutputStream(getFile());writer = new BufferedWriter(new OutputStreamWriter(out));writer.write(content);} catch (Exception e) {e.printStackTrace();} finally {try {if (writer != null) {writer.flush();writer.close();}if (out != null)out.close();} catch (IOException e) {e.printStackTrace();}}}/*** 加载文件内容* @return*/public static String load() {FileInputStream in = null;BufferedReader reader = null;StringBuilder content = new StringBuilder();try {//设置将要打开的存储文件名称in = new FileInputStream(getFile());//FileInputStream -> InputStreamReader ->BufferedReaderreader = new BufferedReader(new InputStreamReader(in));String line = new String();//读取每一行数据,并追加到StringBuilder对象中,直到结束while ((line = reader.readLine()) != null) {content.append(line);}} catch (IOException e) {e.printStackTrace();} finally {try {if (reader != null) {reader.close();}if (in != null) in.close();} catch (IOException e) {e.printStackTrace();}}Log.d(TAG, "load: "+ content.toString());return content.toString();}

Android6.0要验证权限

 /*** * 【动态申请SD卡读写的权限】* * Android6.0之后系统对权限的管理更加严格了,不但要在AndroidManifest中添加,还要在应用运行的时候动态申请* ***/private static final int REQUEST_EXTERNAL_STORAGE = 1;private static String[] PERMISSON_STORAGE = {"android.permission.READ_EXTERNAL_STORAGE","android.permission.WRITE_EXTERNAL_STORAGE"};public static void verifyStoragePermissions(Activity activity) {try {int permission = ActivityCompat.checkSelfPermission(activity, "android.permission.WRITE_EXTERNAL_STORAGE");if (permission != PackageManager.PERMISSION_GRANTED) {/**【判断是否已经授予权限】**/ActivityCompat.requestPermissions(activity, PERMISSON_STORAGE, REQUEST_EXTERNAL_STORAGE);}} catch (Exception e) {e.printStackTrace();}}

 

更多推荐

Android 文件读写 + 申请权限

本文发布于:2024-03-08 15:43:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1721328.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:权限   文件   Android

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!