How to find a file size in KB in android?

By | August 21, 2011

This sample helps you to find the size of a file in KiloBytes.
Here I am pushing a video file on to the device using this method and trying to find it’s size.
Make sure you give the exact file name because file name is case sensitive and push the file only in the sdcard directory in the FileExplorer.
Here is the code.

package pack.coderzheaven;

import java.io.File;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class VideoLengthDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        try{
             File file = new File("/sdcard/my_video.mp4");
             long length = file.length();
             length = length/1024;
             System.out.println("File Path : " + file.getPath() + ", File size : " + length +" KB");
        }catch(Exception e){
        	System.out.println("File not found : " + e.getMessage() + e);
        }
    }
}

Check the LogCat for the output.

Leave a Reply

Your email address will not be published. Required fields are marked *