Is it possible to easily get the size of a folder on the SD card? I use a folder for caching of images, and would like to present the total size of all cached images. Is there a way to this other than iterating over each file? They all reside inside the same folder?
Go to Windows Explorer and right-click on the file, folder or drive that you're investigating. From the menu that appears, go to Properties. This will show you the total file/drive size. A folder will show you the size in writing, a drive will show you a pie chart to make it easier to see.
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.
Just Click on the small “i” button. Actually it contains file “information” in it. 4. Now as you can see all the details of the particular file including the file size.
The Android folder in SD Card is a special hidden folder that your app can use to store application-specific data, such as configuration files. The application data folder is automatically created when you attempt to create a file in it. Use this folder to store any files that the user shouldn't directly interact with.
Just go through all files and sum the length of them:
/** * Return the size of a directory in bytes */ private static long dirSize(File dir) { if (dir.exists()) { long result = 0; File[] fileList = dir.listFiles(); if (fileList != null) { for(int i = 0; i < fileList.length; i++) { // Recursive call if it's a directory if(fileList[i].isDirectory()) { result += dirSize(fileList[i]); } else { // Sum the file size in bytes result += fileList[i].length(); } } } return result; // return the file size } return 0; }
NOTE: Function written by hand so it could not compile!
Here's some code that avoids recursion, and also calculates the physical size instead of the logical size:
public static long getFileSize(final File file) { if (file == null || !file.exists()) return 0; if (!file.isDirectory()) return file.length(); final List<File> dirs = new LinkedList<>(); dirs.add(file); long result = 0; while (!dirs.isEmpty()) { final File dir = dirs.remove(0); if (!dir.exists()) continue; final File[] listFiles = dir.listFiles(); if (listFiles == null || listFiles.length == 0) continue; for (final File child : listFiles) { result += child.length(); if (child.isDirectory()) dirs.add(child); } } return result; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With