我们如何处理低设备内存(内部/外部内存)上的文件保存。我知道如果没有足够的空间,操作系统会抛出 IOException,但有什么方法可以优雅地处理这个问题。
问问题
1501 次
3 回答
1
您尝试以下功能来检查内部存储器的可用性。
/** * This function find outs the free space for the given path. * * @return Bytes. Number of free space in bytes. */ public static long getFreeSpace() { try { if (Environment.getExternalStorageDirectory() != null && Environment.getExternalStorageDirectory().getPath() != null) { StatFs m_stat = new StatFs(Environment.getExternalStorageDirectory().getPath()); long m_blockSize = m_stat.getBlockSize(); long m_availableBlocks = m_stat.getAvailableBlocks(); return (m_availableBlocks * m_blockSize); } else { return 0; } } catch (Exception e) { e.printStackTrace(); return 0; } }
使用上述函数作为 belo :
int m_fileSizeInKB = m_fileSize / 1024; if (m_fileSize >= getFreeSpace()) { //Show the message to user that there is not enough space available in device. } else { //your business logic here. }
于 2013-04-18T07:16:55.460 回答
1
首先找到内部和外部内存空间的可用空间..然后检查您的文件大小小于可用内存(根据您的要求选择内部或外部)然后存储否则消息警报显示...如果您需要格式大小然后使用功能格式大小....
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 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 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-04-18T06:53:15.430 回答
1
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-04-18T06:54:34.773 回答