Android读写文件工具类详解

作者:lyl0530 时间:2021-10-08 18:08:12 

本文实例为大家分享了Android读写文件工具类的具体代码,供大家参考,具体内容如下


public class Utils {
 private static String path1 = Environment.getExternalStorageDirectory().getAbsolutePath();
 private static String path2 = Environment.getDownloadCacheDirectory().getAbsolutePath();
 private static String pathExt = "/111/222/333/444/555/";
 private static String fileName = "6.txt";

public static void write(String str) {
   String filePath = null;
   boolean hasSDCard =Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
   if (hasSDCard) {
     filePath = path1 + pathExt + fileName;
   } else {
     filePath = path2 + pathExt + fileName;
   }
   try {
     File file = new File(filePath);
     if (!file.exists()) {
       //mkdirs()方法生成多层文件夹
       //mkdir()方法生成一层层文件夹
//        File dir = new File(file.getParent());
//        dir.mkdirs();
       file.getParentFile().mkdirs();//生成文件外层的文件夹
       file.createNewFile();//生成文件
     }
     FileOutputStream os = new FileOutputStream(file);
     os.write(str.getBytes());
     os.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }

public static String read() {
   String content = "";
   String filePath;

boolean sdcard = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
   if (sdcard) {
     filePath = path1 + pathExt + fileName;
   } else {
     filePath = path2 + pathExt + fileName;
   }
   try {
     File file = new File(filePath);
     if (file.exists()) {
       FileInputStream is = new FileInputStream(file);
       InputStreamReader inputReader = new InputStreamReader(is);//设置流读取方式
       BufferedReader buffReader = new BufferedReader(inputReader);
       String line;
       try {
         while (null != (line = buffReader.readLine())) {
           content += line + "\n";//读取的文件容
         }
         is.close();//关闭输入流
       } catch (IOException e) {
         e.printStackTrace();
       } finally {
         try {
           if (null != is) {
             is.close();
           }
         } catch (IOException e) {
           e.printStackTrace();
         }
       }
     }
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   }
   return content;
 }
}

1. 清单文件中添加读写权限


<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

2.Android6.0以上版本要动态申请读写权限


ArrayList<String> permissionList = new ArrayList<>();
private String[] permissions = {
"android.permission.READ_EXTERNAL_STORAGE",
"android.permission.WRITE_EXTERNAL_STORAGE" };
//检测是否有写的权限
//判断手机版本,如果低于6.0 则不用申请权限,直接拍照
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(permissions[0]) != PackageManager.PERMISSION_GRANTED) {
permissionList.add(permissions[0]);
}
if (checkSelfPermission(permissions[1]) != PackageManager.PERMISSION_GRANTED) {
permissionList.add(permissions[1]);
}

if (!permissionList.isEmpty()) {
String[] permissions1 = permissionList.toArray(new String[permissionList.size()]);
requestPermissions(permissions1, 1);
} else {
Utils.write("balabala");
Utils.read();
}
} else {
Utils.write("balabala");
Utils.read();
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case 1:
 if (PackageManager.PERMISSION_GRANTED == grantResults[0]){
 Utils.write("balabala");
 Utils.read();
 } else {
 Log.d(TAG, "fail: ");
 }
 break;
}
}

来源:https://blog.csdn.net/lyl0530/article/details/104863777

标签:Android,读写文件,工具类
0
投稿

猜你喜欢

  • Android中Handler引起的内存泄露问题解决办法

    2023-11-08 23:40:58
  • Android中断线程的处理方法

    2023-07-31 11:51:55
  • C#控制台实现飞行棋小游戏

    2023-04-27 05:13:43
  • Java自定义注解用法实例小结

    2023-03-26 09:13:51
  • Java控制台输入数组并逆序输出的方法实例 <font color=red>原创</font>

    2023-07-13 23:32:26
  • Android Notification的多种用法总结

    2021-07-27 02:31:00
  • C/C++在Java、Android和Objective-C三大平台下实现混合编程

    2022-01-04 16:58:08
  • Spring/SpringBoot @RequestParam注解无法读取application/json格式数据问题解决

    2023-11-26 11:26:29
  • Java全面细致讲解Cookie与Session及kaptcha验证码的使用

    2021-09-03 23:10:56
  • 详解Java中用于查找对象哈希码值的hashCode()函数

    2023-09-17 02:52:19
  • C++普通函数指针与成员函数指针实例解析

    2022-09-29 10:19:36
  • C# 中使用正则表达式匹配字符的含义

    2023-11-19 02:59:38
  • android获取手机cpu并判断是单核还是多核

    2021-09-28 22:11:24
  • 简述Java List去重五种方法

    2022-02-28 03:17:13
  • 浅谈java内存管理与内存溢出异常

    2022-04-22 15:03:18
  • c语言switch反汇编的实现

    2023-06-29 03:38:17
  • Android应用开发中自定义ViewGroup视图容器的教程

    2023-05-29 18:14:45
  • C# 操作符之二 算数操作符

    2023-06-19 20:21:13
  • 使用Stargate访问K8ssandra的过程之Springboot整合Cassandra

    2022-02-08 23:12:25
  • Java类之间的关系图_动力节点Java学院整理

    2022-07-31 23:03:46
  • asp之家 软件编程 m.aspxhome.com