Home Java Example Java Io Getting the Size of a File in Java



Getting the Size of a File in Java
Posted on: April 16, 2007 at 12:00 AM
In this section you will learn how to get the size of any file.

Java file get size

In this section, you will learn how to get the size of a file.

Description of code:

You can see in the given example, we have created an object of File class and specified a file in the constructor. The object then calls the method length() which returns the size of the file in bytes. Then we have converted the size of file from bytes to kilo bytes.

Here is the code:

import java.io.*;

public class FileSize {
	public static void main(String args[]) {
		File file = new File("C:/java.txt");
		long filesize = file.length();
		long filesizeInKB = filesize / 1024;
		System.out.println("Size of File is: " 
		+ filesizeInKB + " KB");
	}
}

Through the method length(), you can get the size of any file. This method returns the size in bytes.

Output:

Size of File is: 1 KB


Download this example.

Related Tags for Getting the Size of a File in Java:
cfiletextmethodssizemethodsedgetcharnumberbytethischaractercharactersiftexexamplecteprogramtobyteslearnrambaseexamearexteilitlscanusewiseinasmoutcabasedesasemeproxaxampsatracishallivmpleaaractxtwiszssthabhatpleplprodsogro


More Tutorials from this section

Ask Questions?    Discuss: Getting the Size of a File in Java   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.