Android文件、内存、SDCard管理常用工具类、方法

    技术2024-12-11  14

    在编程的时候发现收集整理一些常用的工具类对于开发非常的有用,非常能锻炼自己归纳整理的能力,在以后使用的时候也非常的方便

    SDCard管理的工具类MemoryStatusUtil 

     

     

    public class MemoryStatus { static final int ERROR = -1; static public boolean externalMemoryAvailable() { return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); } static public long getAvailableInternalMemorySize() { File path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long availableBlocks = stat.getAvailableBlocks(); return availableBlocks * blockSize; } static public long getTotalInternalMemorySize() { File path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long totalBlocks = stat.getBlockCount(); return totalBlocks * blockSize; } static public long getAvailableExternalMemorySize() { if(externalMemoryAvailable()) { File path = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long availableBlocks = stat.getAvailableBlocks(); return availableBlocks * blockSize; } else { return ERROR; } } static public long getTotalExternalMemorySize() { if(externalMemoryAvailable()) { File path = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long totalBlocks = stat.getBlockCount(); return totalBlocks * blockSize; } else { return ERROR; } } static public String formatSize(long size) { String suffix = null; if (size >= 1024) { suffix = "KiB"; size /= 1024; if (size >= 1024) { suffix = "MiB"; size /= 1024; } } StringBuilder resultBuffer = new StringBuilder(Long.toString(size)); int commaOffset = resultBuffer.length() - 3; while (commaOffset > 0) { resultBuffer.insert(commaOffset, ','); commaOffset -= 3; } if (suffix != null) resultBuffer.append(suffix); return resultBuffer.toString(); } }  

    未完待续,这个工具类的整理会不断的添加和整理:

    对于文件大小的格式化操作如果想要更准确些,可以采用下面的方式,精确到小数点后面:

    private static String formatFileSize(long filesize) { DecimalFormat df = new DecimalFormat("#.##"); if (filesize >= 1024d * 1024d * 0.8d) return df.format(filesize / (1024d * 1024d)) + "M"; else if (filesize >= 1024d * 0.8d) return df.format(filesize / 1024d) + "K"; else if (filesize == 0) return df.format(filesize) + "Byte"; return df.format(filesize) + "Bytes"; } 

     

    最新回复(0)