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