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(); ...

Get Java™ Phrasebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.