O'Reilly logo

Java™ Phrasebook by Timothy Fisher

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Getting the Size of a File

File file = new File("infilename");
											long length = file.length();

In this phrase, we get the size of a file using the length() method on the File object. The length()method will return the size of the file in bytes. If the file does not exist, a value of 0 is returned.

This method is often convenient to use prior to reading a file into a byte array. Using the length() method, you can determine the length of the file so that you know how large of a byte array you will need to hold the entire file contents. For example, the following code is often used for reading a file into a byte array:

File myFile = new File("myfile.bin"); InputStream is = new FileInputStream(myFile); // Get the size of the file long length = myFile.length(); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required