如何确定内部存储是否已满?

时间:2013-05-23 09:23:57

标签: android storage

我正在制作一个Android应用程序,可以在内部存储中保存2MB .txt个文件。如何知道内部存储器是否已满,从而将文件保存到外部存储器?

3 个答案:

答案 0 :(得分:3)

快速搜索后,我找到了以下方法。你可以从StatFs课程中获得它。此类用于检索有关文件系统空间的整体信息。

public int FreeMemory()
{
    StatFs statFs = new StatFs(Environment.getRootDirectory().getAbsolutePath());
    int Free  = (statFs.getAvailableBlocks() * statFs.getBlockSize()) / 1048576;
    return Free;
}

您也可以通过以下方式找到

File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
return Formatter.formatFileSize(this, availableBlocks * blockSize);

您可以从herehere too获取更多详细信息。

我希望这会对你有所帮助。谢谢。

答案 1 :(得分:1)

请检查以下代码(我已将其复制到此网站,但我不记得它在哪里)

public static boolean externalMemoryAvailable() {
    return android.os.Environment.getExternalStorageState().equals(
            android.os.Environment.MEDIA_MOUNTED);
}

public static String getAvailableInternalMemorySize() {
    File path = Environment.getDataDirectory();
    StatFs stat = new StatFs(path.getPath());
    long blockSize = stat.getBlockSize();
    long availableBlocks = stat.getAvailableBlocks();
    return formatSize(availableBlocks * blockSize);
}

public static String getTotalInternalMemorySize() {
    File path = Environment.getDataDirectory();
    StatFs stat = new StatFs(path.getPath());
    long blockSize = stat.getBlockSize();
    long totalBlocks = stat.getBlockCount();
    return formatSize(totalBlocks * blockSize);
}

public static String getAvailableExternalMemorySize() {
    if (externalMemoryAvailable()) {
        File path = Environment.getExternalStorageDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return formatSize(availableBlocks * blockSize);
    } else {
        return ERROR;
    }
}

public static String getTotalExternalMemorySize() {
    if (externalMemoryAvailable()) {
        File path = Environment.getExternalStorageDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long totalBlocks = stat.getBlockCount();
        return formatSize(totalBlocks * blockSize);
    } else {
        return ERROR;
    }
}

public static String formatSize(long size) {
    String suffix = null;

    if (size >= 1024) {
        suffix = "KB";
        size /= 1024;
        if (size >= 1024) {
            suffix = "MB";
            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();
}

希望能帮助你。

答案 2 :(得分:0)

你试过float freeSpace = DeviceMemory.getInternalFreeSpace();吗?