The correct method for obtaining the file size in Java, and java for obtaining the file size

Source: Internet
Author: User

[Switch] the correct method for obtaining the file size in Java, java for obtaining the file size

Source: http://blog.csdn.net/chaijunkun/article/details/22387305. I will sort out relevant blog posts from time to time and improve the relevant content. Therefore, we strongly recommend that you view this article in the original source.


When writing code today, You need to implement the function of obtaining the File size. Currently, there are two implementation methods: the length () method of File, and the available () method of FileInputStream () when InputStream does not perform the read operation, the available () size should be equal to the file size. However, when processing large files, the latter may have problems. Let's take a look:


In this example, I used the CentOS 6.5 installation image file, mainly considering that the file is large enough (greater than 2 GB ).

1. Use the length () method of File

public static void main(String[] args) {    File f= new File("D:\\CentOS-6.5-x86_64-bin-DVD1.iso");    if (f.exists() && f.isFile()){        logger.info(f.length());    }else{        logger.info("file doesn't exist or is not a file");    }}

Let's take a look at the output:

4467982336

The result is 4.16 GB, consistent with that displayed on Windows.

 

Next, let's take a look at the file size obtained through FileInputStream:

public static void main(String[] args) {    FileInputStream fis= null;    try{        File f= new File("D:\\CentOS-6.5-x86_64-bin-DVD1.iso");        fis= new FileInputStream(f);        logger.info(fis.available());    }catch(Exception e){        logger.error(e);    } finally{        if (null!=fis){            try {                fis.close();            } catch (IOException e) {                logger.error(e);            }        }    }}

The running result is as follows:

2147483647

 

Is this result quite familiar? It is Integer. MAX_VALUE, that is, the maximum value that a signed Integer can represent.

Convert to a familiar unit. What is the size of the file obtained in this way?

About 2 GB. This is obviously not the correct result.

 

The reason is that the type returned by the length () method of File is long, and the maximum positive number that long can represent is 9223372036854775807. The maximum supported File size is 8954730132868714 EB, this magnitude will be used in the history of human IT development for many years, while the returned value of the FileInputStream avaliable () method is int. We also introduced the largest representation range before, the maximum file size supported is 1.99 GB, which is easily reached now.

 

Supplement:

Reading large files by Using Streaming methods is not unfeasible, but cannot use traditional java. io. * The package. java is used here. nio. * The new tool-FileChannel. The following shows the sample code:

public static void main(String[] args) {    FileChannel fc= null;    try {        File f= new File("D:\\CentOS-6.5-x86_64-bin-DVD1.iso");        if (f.exists() && f.isFile()){            FileInputStream fis= new FileInputStream(f);            fc= fis.getChannel();            logger.info(fc.size());        }else{            logger.info("file doesn't exist or is not a file");        }    } catch (FileNotFoundException e) {        logger.error(e);    } catch (IOException e) {        logger.error(e);    } finally {        if (null!=fc)){            try{                fc.close();            }catch(IOException e){                logger.error(e);            }        }     }}

 

The results obtained after FileChannel are consistent with the first case, which accurately describes the file size.


I would also like to remind all technical colleagues that when reading large files, you must be cautious about int-type data to avoid hidden bugs and difficult to locate.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.