how do I get file size of temp file in android?
Solution 1:
I hope this can help you:
File file = new File(selectedPath);
int file_size = Integer.parseInt(String.valueOf(file.length()/1024));
Where the String selectedPath
is the path to the file whose file size you want to determine.
file.length()
returns the length of the file in bytes, as described in the Java 7 Documentation:
Returns the length, in bytes, of the file denoted by this abstract pathname, or 0L if the file does not exist. Some operating systems may return 0L for pathnames denoting system-dependent entities such as devices or pipes.
Dividing by 1024 converts the size from bytes to kibibytes. kibibytes = 1024 bytes.
Solution 2:
Kotlin Extension Solution
Add these somewhere, then call myFile.sizeInMb
or whichever you need
val File.size get() = if (!exists()) 0.0 else length().toDouble()
val File.sizeInKb get() = size / 1024
val File.sizeInMb get() = sizeInKb / 1024
val File.sizeInGb get() = sizeInMb / 1024
val File.sizeInTb get() = sizeInGb / 1024
If you need a File from a String or Uri, try adding these
fun Uri.asFile(): File = File(toString())
fun String?.asUri(): Uri? {
try {
return Uri.parse(this)
} catch (e: Exception) {
}
return null
}
If you'd like to easily display the values as a string, these are simple wrappers. Feel free to customize the default decimals displayed
fun File.sizeStr(): String = size.toString()
fun File.sizeStrInKb(decimals: Int = 0): String = "%.${decimals}f".format(sizeInKb)
fun File.sizeStrInMb(decimals: Int = 0): String = "%.${decimals}f".format(sizeInMb)
fun File.sizeStrInGb(decimals: Int = 0): String = "%.${decimals}f".format(sizeInGb)
fun File.sizeStrWithBytes(): String = sizeStr() + "b"
fun File.sizeStrWithKb(decimals: Int = 0): String = sizeStrInKb(decimals) + "Kb"
fun File.sizeStrWithMb(decimals: Int = 0): String = sizeStrInMb(decimals) + "Mb"
fun File.sizeStrWithGb(decimals: Int = 0): String = sizeStrInGb(decimals) + "Gb"
Solution 3:
Try to use below code:
// Get file from file name
final String dirPath = f.getAbsolutePath();
String fileName = url.substring(url.lastIndexOf('/') + 1);
File file = new File(dirPath + "/" + fileName);
// Get length of file in bytes
long fileSizeInBytes = file.length();
// Convert the bytes to Kilobytes (1 KB = 1024 Bytes)
long fileSizeInKB = fileSizeInBytes / 1024;
// Convert the KB to MegaBytes (1 MB = 1024 KBytes)
long fileSizeInMB = fileSizeInKB / 1024;
if (fileSizeInMB > 27) {
...
}
Hope It will work for you..!!