In many cases, we need to create sub-directories in the SD card directory to store image files and so on, some people asked me how to create sub-folders under the SD card, today is an example, that is, when the program is abnormal, how to write the exception in the specified file, of course, here only how to create a folder,
Code
public class Mainactivity extends Activity {
private static final String TAG = "mainactivity";
@Override
protected void OnCreate (Bundle savedinstancestate) {
Setcontentview (R.layout.activity_main);
Super.oncreate (savedinstancestate);
/**
* This is your root directory in the diary to create the file and write the data to the file
*/
String path = Getlogrootpath ();
StringBuffer sb = new StringBuffer ();
Sb.append (Path). Append (File.separator). Append ("Log.txt");
File File = new file (sb.tostring ());
try {
FileOutputStream fos = new FileOutputStream (file);
Fos.write ("Hahahha". GetBytes ());
Fos.close ();
} catch (FileNotFoundException e) {
E.printstacktrace ();
} catch (IOException e) {
E.printstacktrace ();
}
}
/**
* Determine if there is an SD card
* @return
*/
public Boolean issdcardavaiable () {
if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {
return true;
}
return false;
}
/**
* Get the journal root directory
* @return
*/
Public String Getlogrootpath () {
String Sdcardpath = Getsdpath ();
StringBuffer sb = new StringBuffer ();
Sb.append (Sdcardpath). Append (File.separator). Append ("Zgzh");
Sb.append (File.separator). Append ("Logs");
String root = sb.tostring ();
File Sdfile = new file (sb.tostring ());
if (!sdfile.exists () | | | Sdfile.getabsolutefile () ==null) {
Sdfile.mkdirs ();
}
return root;
}
/**
* Get the path to the SD card
* @return
*/
Private String Getsdpath () {
File file = null;
if (issdcardavaiable ()) {
File = Environment.getexternalstoragedirectory ();
}else{
File = Environment.getrootdirectory ();
}
if (file!=null&&! Textutils.isempty (File.getpath ())) {
return File.getpath ();
}else{
return "/sdcard";
}
}
}
Remember to add permissions:
<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
How Android creates a specified multi-tiered folder under an SD card