在android中对文件夹和文件的读写,与java是相同的,不过android上运行需要指明用户的权限。修改AndroidManifest.xml文件,添加如下配置:
<!-- 往sdcard中写入数据的权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" ></uses-permission>
<!-- 在sdcard中创建/删除文件的权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" ></uses-permission>
这样配置后就可以在真机上像Java一样操作文件和文件夹了:
public class SDCardHelper {
public static void deleteDirectory(String path) {
File dir = new File(path);
if (dir.exists()) {
dir.delete();
}
}
public static boolean createDirectory(String path) {
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
if (dir.exists()) {
return true;
} else {
return false;
}
}
public static String getDirectory(String subDir) {
String path = android.os.Environment.getExternalStorageDirectory()
.getAbsolutePath() + File.separator;
return path + subDir;
}
public static boolean hasSDCard() {
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED)) {
return true;
} else {
return false;
}
}
}