如何在设备内存(内部/外部内存)较低的情况下处理文件保存。我知道如果没有足够的空间,操作系统会抛出IOException异常,但是否有一种优雅地处理这种情况的方法。
如何在设备内存(内部/外部内存)较低的情况下处理文件保存。我知道如果没有足够的空间,操作系统会抛出IOException异常,但是否有一种优雅地处理这种情况的方法。
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();
}
谢谢
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
return Formatter.formatFileSize(this, availableBlocks * blockSize);
您可以尝试以下函数来检查内部存储器的可用性。
/**
* 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;
}
}
使用上面的函数如下:
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.
}