The Revguin
The Revguin

Reputation: 17

Java - file.length() returns 0

For some reason, even after doing a file.exists() check, the value comes off as 0, even thou im sure that these directories aren't empty, since I've checked c:\ included.

 File folder = new File(directama);
    File[] listOfFiles=folder.listFiles();

    for (File listOfFile : listOfFiles) {

    if(listOfFile.exists()){    

        String str = tamanhovari.getText();          //IRRELEVANT
        Long valisizeGB = parseLong(str);            //IRRELEVANT   
        String length = valueOf(listOfFile.length());//IRRELEVANT
        Long bytevalue = parseLong(length);          //IRRELEVANT    
        String gbdivisor ="10737418284";             //IRRELEVANT
        Long bytetogb = parseLong(gbdivisor);       //IRRELEVANT
        Long valisizeBT=valisizeGB*bytetogb;        //IRRELEVANT
        Long actualfilesize = bytevalue/bytetogb;   //IRRELEVANT

        if (listOfFile.length()<= valisizeBT) {
            if(listOfFile.isFile()){
            }
            else if (listOfFile.isDirectory()) {
                model.addRow(new Object[]{listOfFile.getName(),actualfilesize + " GB" });
            }
            else{}

    }}
    else{}
    }

it SHOULD logically return the value of the folder in GB's, but even when I remove the GB formating, and try returning only the byte value, it still only returns 0.

Any suggestions? I've pretty much done almost everything.

EDIT: SOLVED! Thanks for the quick responses! To retrieve the size of a folder, one must use file.sizeOfDirectory() and not file.length()

Upvotes: 0

Views: 4500

Answers (3)

nablex
nablex

Reputation: 4757

Please read the specs:

The return value is unspecified if this pathname denotes a directory. 

Upvotes: 3

alain.janinm
alain.janinm

Reputation: 20065

You have to read the actual lenght of a file not a directory. According to the documentation :

The return value is unspecified if this pathname denotes a directory.

Return the length, in bytes, of the file denoted by this abstract pathname, or 0L if the file does not exist. Some operating systems may return 0L for pathnames denoting system-dependent entities such as devices or pipes.

Upvotes: 0

peterremec
peterremec

Reputation: 516

Javadoc of "length" method:

Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory.

Upvotes: 0

Related Questions