1

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

4

3 回答 3

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);

您也可以从这里这里获得更多详细信息。

我希望这能帮到您。谢谢你。

于 2013-05-23T09:47:07.723 回答
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();
}

希望帮助你。

于 2013-05-23T11:02:49.197 回答
0

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

于 2013-05-23T09:35:17.520 回答