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(); if (length > Integer.MAX_VALUE) {    // File is too large } byte[] bytes = new byte[(int)length]; int offset = 0; int numRead = 0; while (offset < bytes.length    && (numRead=is.read(bytes, offset, bytes.length- offset)) >= 0) {    offset += numRead; } is.close();





JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net