Example analysis of file operation and logging operation on Android SD card

  • 2021-01-02 21:59:32
  • OfStack

This article illustrates the method of file operation and logging operation on Android SD card. To share for your reference, the details are as follows:


// SD Whether the card exists 
private boolean checkSDCardStatus() {
 boolean SDCardStatus = false;
 String sDStateString = android.os.Environment.getExternalStorageState();
 if (sDStateString.equals(android.os.Environment.MEDIA_MOUNTED)) {
  SDCardStatus = true;
 } else {
  // SD Card is not available 
 }
 return SDCardStatus;
}
// SD Is it on the card APK file 
private boolean checkFileExist(String iFilePath) {
 boolean fileExist = false;
 if (checkSDCardStatus()) {
  File myFile = new File(iFilePath);
  if (myFile.exists()) {
  fileExist = true;
  }
 }
 return fileExist;
}
// Delete the file 
private void deleteApk(String iFilePath) {
 if (checkSDCardStatus()) {
  File myFile = new File(iFilePath);
  if (myFile.exists()) {
  myFile.delete();
  }
 }
}
// in SD Card with txt record 
public static void logOnFile(String format, Object... args){
 String logstr = String.format(format, args);
 SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
 String date  =  sDateFormat.format(new java.util.Date());
 logstr = "/r/n-------------------------/r/n" + date + "/r/n" + logstr;
 FileOutputStream fout;
 DataOutputStream dataout;
 try {
  fout = new FileOutputStream("//sdcard//log.txt",true);
  dataout = new DataOutputStream(fout);
  dataout.writeUTF(logstr);
  dataout.flush();
  dataout.close();
  fout.flush();
  fout.close();
 } catch (FileNotFoundException e) {
  e.printStackTrace();
 } catch (IOException e) {
  e.printStackTrace();
 }
}

I hope this article has been helpful in Android programming.


Related articles: