Android Read and Write File Tool Class Detailed Explanation

  • 2021-11-24 02:50:16
  • OfStack

This article example for everyone to share Android read and write file tool class specific code, for your reference, the specific content is as follows


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() Method to generate multi-layer folders 
        //mkdir() Method generation 1 Layer-by-layer folder 
//        File dir = new File(file.getParent());
//        dir.mkdirs();
        file.getParentFile().mkdirs();// Generate folders on the outer layer of files 
        file.createNewFile();// Generate file 
      }
      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);// Set the stream read mode 
        BufferedReader buffReader = new BufferedReader(inputReader);
        String line;
        try {
          while (null != (line = buffReader.readLine())) {
            content += line + "\n";// File capacity read 
          }
          is.close();// Close the input stream 
        } 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. Add read and write permissions to the manifest file


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

2. Android 6.0 and above should dynamically apply for read and write permissions


ArrayList<String> permissionList = new ArrayList<>();
private String[] permissions = {
 "android.permission.READ_EXTERNAL_STORAGE",
 "android.permission.WRITE_EXTERNAL_STORAGE" };
// Check whether you have write permission 
// Judge the mobile phone version , If it is lower than 6.0  You do not need to apply for permission , Direct photograph 
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;
 }
}

Related articles: