I have a problem getting the size of a file. I have the following code:
File file = new File("/sdcard/lala.txt");
long length = file.length();
And always length is zero, yes zero.
I am using Android SDK (not sure what version), the code is running inside an Activity, I have created an sdcard.
Perhaps it is a permission issue? Is there anything I am missing?
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.
Click the file or folder. Press Command + I on your keyboard. A window opens and shows the size of the file or folder.
Java get file size using File classJava File length() method returns the file size in bytes. The return value is unspecified if this file denotes a directory.
If you need the file size in Kilobytes (KB), just divide the length by 1024 . Similarly, to get the file size in Megabytes (MB), divide the result by 1024 * 1024 . That's all about finding a file's size in bytes in Kotlin.
The File.length()
method returns the following according to the javadoc:
"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."
As you can see, zero can be returned:
My money is on the second case; i.e. that you have the wrong filename / pathname. Try calling File.exists()
on the filename to see what that tells you. The other two cases are possible too, I guess.
(For the record, most /proc/...
files on a Linux-based system also have an apparent file size of zero. And Android is Linux based.)
If you want to get the folder/file size in terms of Kb or Mb then use the following code. It will help in finding the accurate size of your file.
public static String getFolderSizeLabel(File file) {
long size = getFolderSize(file) / 1024; // Get size and convert bytes into Kb.
if (size >= 1024) {
return (size / 1024) + " Mb";
} else {
return size + " Kb";
}
}
This function will return size in form of bytes:
public static long getFolderSize(File file) {
long size = 0;
if (file.isDirectory()) {
for (File child : file.listFiles()) {
size += getFolderSize(child);
}
} else {
size = file.length();
}
return size;
}
I would suggest you to use the following code instead of hard-coding the path ("/sdcard/lala.txt"):
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/lala.txt");
file.length()
You should use:
File file = new File(Uri.parse("/sdcard/lala.txt").getPath());
instead of:
File file = new File("/sdcard/lala.txt");
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