我们在很多情况下都需要在sd卡目录下创建子目录存放图片文件之类的,之前也有人问我怎么在sd卡下创建子文件夹,今天就讲一个例子,就是当程序发生异常的时候,怎么把异常写在指定的文件中,当然在这里只讲如何创建文件夹,
代码
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);
/**
* 这是在日记你根目录创建文件 并写数据到文件中
*/
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();
}
}
/**
* 判断是否有sd卡
* @return
*/
public boolean isSDCardAvaiable(){
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
return true;
}
return false;
}
/**
* 获取日记根目录
* @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;
}
/**
* 获取sd卡的路径
* @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";
}
}
}
记得要加入权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>