Android studio Writes Strings to Local Operation Methods

  • 2021-09-24 23:38:20
  • OfStack

Operations for the File class:

1. First, you need to add relevant permissions:


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

Note that dynamic application is required above 6.0:


private void checkPermission(){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//6.0 Above 
      int permission = ActivityCompat.checkSelfPermission(getApplication(), Manifest.permission.RECEIVE_SMS);
      int permission1 = ActivityCompat.checkSelfPermission(getApplication(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
      if(permission != PackageManager.PERMISSION_GRANTED && permission1 != PackageManager.PERMISSION_GRANTED) {
        Log.e(TAG," No access, please apply ");
        //  Application 1 Permissions (or permissions) and provide the get code (user-defined) used to return the callback )
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
            Manifest.permission.RECEIVE_SMS) && ActivityCompat.shouldShowRequestPermissionRationale(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE)) {// Here you can write a dialog box or something to explain to the user why you want to apply for permission, and then apply for permission again at the confirmation key of the dialog box 
          Log.e(TAG," Prompt ");
          ActivityCompat.requestPermissions(this,
              new String[]{Manifest.permission.RECEIVE_SMS,Manifest.permission.WRITE_EXTERNAL_STORAGE}, CODE_READ_SMS);
        } else {
          // To apply for permission, the string array is 1 One or more permissions to apply for, 1 Is the return parameter of the permission application result, which is in the onRequestPermissionsResult You can know the application results 
          Log.e(TAG," You have disabled ");
          Toast.makeText(MainActivity.this," You did not get the permission to read the mobile phone. Please go to the application center to open the permission manually ",Toast.LENGTH_SHORT).show();
        }
      }else{
         Log.e(TAG," Got permission ");
      }
    }else{
      Log.e(TAG," Got permission ");
    }
  }
  @Override
  public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(requestCode == CODE_READ_SMS){
      if(grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        Log.e(TAG," Got permission ");
      } else{
        //  Do not get permission, do special treatment 
        Log.e(TAG," No access was obtained ");
        Toast.makeText(MainActivity.this," You did not get the permission to read the mobile phone. Please go to the application center to open the permission manually ",Toast.LENGTH_SHORT).show();
      }
    }
  }

2.saveToFile

a) BufferedWriter appended


// Save the file to sd Card 
  public void saveToFile(String content) {
    BufferedWriter out = null;

    // Get SD Card status 
    String state = Environment.getExternalStorageState();
    // Judge SD Is the card ready 
    if (!state.equals(Environment.MEDIA_MOUNTED)) {
      Toast.makeText(this, " Please check SD Card ", Toast.LENGTH_SHORT).show();
      return;
    }
    // Acquire SD Card root directory 
    File file = Environment.getExternalStorageDirectory();
    try {
      Log.e(TAG, "======SD Card root directory: " + file.getCanonicalPath());
      if(file.exists()){
        LOG.e(TAG, "file.getCanonicalPath() == " + file.getCanonicalPath());
      }
      /*
       Construction parameters of output stream 1 : Can be File Object   It can also be a file path 
       Construction parameters of output stream 2 Default to False=> Covering content;  true=> Additional content 
       */
      out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file.getCanonicalPath() + "/readMsg.txt",true)));
      out.newLine();
      out.write(content);
      Toast.makeText(this, " Save successfully ", Toast.LENGTH_SHORT).show();

    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (out != null) {
        try {
          out.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }

b) FileWriter appended


 /**
   *  Use FileWriter Append text content 
   * @param file
   * @param content
   */
  private void addTxtToFileWrite(File file, String content){
    FileWriter writer = null;
    try {
      //FileWriter(file, true), No. 1 2 Parameters are true Is additional content, false Is an overlay 
      writer = new FileWriter(file, true);
      writer.write("\r\n");// Line break 
      writer.write(content);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if(writer != null){
          writer.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}

3.readFromFile()


// From SD Card reading file 
  public String readFromFile() {
    // Use character stream when reading    Ten thousand 1 It has Chinese in it 
    BufferedReader reader = null;
    FileInputStream fis;
    StringBuilder sbd = new StringBuilder();
    String state = Environment.getExternalStorageState();
    if (!state.equals(Environment.MEDIA_MOUNTED)) {
      Toast.makeText(this, "SD Card not ready ", Toast.LENGTH_SHORT).show();
      return "";
    }
    File root = Environment.getExternalStorageDirectory();
    try {
      fis = new FileInputStream(root + "/readMsg.txt");
      reader = new BufferedReader(new InputStreamReader(fis));
      String row;
      while ((row = reader.readLine()) != null) {
        sbd.append(row);
      }
    } catch (FileNotFoundException e) {
      Toast.makeText(this, " File does not exist ", Toast.LENGTH_SHORT).show();
      //e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return sbd.toString();
  }

4.removeFromFile()


// Delete SD Card file 
  public void removeFromFile() {
    String state = Environment.getExternalStorageState();
    if (!state.equals(Environment.MEDIA_MOUNTED)) {
      Toast.makeText(this, "SD Card not ready ", Toast.LENGTH_SHORT).show();
      return;
    }
    // Acquire SD Card root directory 
    File root = Environment.getExternalStorageDirectory();
    File myFile=new File(root+"/sd.txt");
    //File myFile=new File(root,"sd.txt");
    if (myFile.exists()) {
      myFile.delete();
      Toast.makeText(this," File deleted ",Toast.LENGTH_SHORT).show();
    }else {
      Toast.makeText(this," File does not exist ",Toast.LENGTH_SHORT).show();
    }
  }
}

Summarize


Related articles: