首页 > 代码库 > Android得到SD卡文件夹大小以及删除文件夹操作

Android得到SD卡文件夹大小以及删除文件夹操作

float cacheSize = dirSize(new File(Environment.getExternalStorageDirectory() + AppConstants.APP_CACHE_FOLDER)) / 1024.0f / 1024.0f;tvCacheSize.setText(((int) (cacheSize * 100)) / 100.0f + "M");/*** Return the size of a directory in bytes*/private long dirSize(File dir) {if (dir.exists()) {long result = 0;File[] fileList = dir.listFiles();for (int i = 0; i < fileList.length; i++) {// Recursive call if it‘s a directoryif (fileList[i].isDirectory()) {result += dirSize(fileList[i]);} else {// Sum the file size in bytesresult += fileList[i].length();}}return result; // return the file size}return 0;}case R.id.clearCacheLayout:try {DeleteRecursive(new File(Environment.getExternalStorageDirectory() + AppConstants.APP_CACHE_FOLDER));Toast.makeText(mActivity, "缓存已清除", Toast.LENGTH_SHORT).show();float cacheSize = dirSize(new File(Environment.getExternalStorageDirectory() + AppConstants.APP_CACHE_FOLDER)) / 1024.0f / 1024.0f;tvCacheSize.setText(((int) (cacheSize * 100)) / 100 + "M");} catch (Exception e) {e.printStackTrace();}break;/** * 删除某个文件夹下的所有文件夹和文件 * * @param delpath */private void DeleteRecursive(File fileOrDirectory) {if (fileOrDirectory.isDirectory())for (File child : fileOrDirectory.listFiles())DeleteRecursive(child);fileOrDirectory.delete();}

 读取Assets文件内容

//从assets 文件夹中获取文件并读取数据public String getFromAssets(String fileName){   String result = "";   try {InputStream in = getResources().getAssets().open(fileName);//获取文件的字节数int lenght = in.available();//创建byte数组byte[]  buffer = new byte[lenght];//将文件中的数据读到byte数组中in.read(buffer);result = EncodingUtils.getString(buffer, ENCODING);} catch (Exception e) {e.printStackTrace();}return result;}}

 

Android得到SD卡文件夹大小以及删除文件夹操作