获取文件夹大小

时间:2010-07-02 22:05:42

标签: java file-io

您知道如何在Java中获取文件夹大小?

File类中的length()方法仅适用于文件,使用该方法我总是得到0的大小。

8 个答案:

答案 0 :(得分:28)

使用apache-commons-io,FileUtils类有一个sizeOfDirectory方法

答案 1 :(得分:21)

import java.io.File;
import org.apache.commons.io.FileUtils;

public class FolderSize
{
  public static void main(String[] args)
   {
    long size = FileUtils.sizeOfDirectory(new File("C:/Windows/folder"));

    System.out.println("Folder Size: " + size + " bytes");
   }
}

答案 2 :(得分:7)

import java.io.File;

public class GetFolderSize {

    int totalFolder = 0;
    int totalFile = 0;

    public static void main(String args[]) {
        String folder = "C:/GetExamples";
        try {
            GetFolderSize size = new GetFolderSize();
            long fileSizeByte = size.getFileSize(new File(folder));
            System.out.println("Folder Size: " + fileSizeByte + " Bytes");
            System.out.println("Total Number of Folders: "
                + size.getTotalFolder());
            System.out.println("Total Number of Files: " + size.getTotalFile());
        } catch (Exception e) {}
    }

    public long getFileSize(File folder) {
        totalFolder++;
        System.out.println("Folder: " + folder.getName());
        long foldersize = 0;
        File[] filelist = folder.listFiles();
        for (int i = 0; i < filelist.length; i++) {
            if (filelist[i].isDirectory()) {
                foldersize += getFileSize(filelist[i]);
            } else {
                totalFile++;
                foldersize += filelist[i].length();
            }
        }
        return foldersize;
    }

    public int getTotalFolder() {
        return totalFolder;
    }

    public int getTotalFile() {
        return totalFile;
    }
}

答案 3 :(得分:4)

简单地递归迭代所有子文件夹会出现轻微错误。在某些文件系统上,可以使用符号链接创建循环目录结构,如下所示:

mkdir -- parents father/son
ln -sf ${PWD}/father father/son
ls father/son/father/son/father/son/father/son/

要防止出现此错误,可以使用java.io.File#getCanonicalPath方法。以下代码略微修改了previous answer

public static long getFileSize(File folder) throws IOException {
    return ( getFileSize ( folder , new HashSet < String > ( ) ) ) ;
}

public static long getFileSize(File folder, Set<String> history)
        throws IOException {
    long foldersize = 0;
    File[] filelist = folder.listFiles();
    for (int i = 0; i < filelist.length; i++) {
        System.err.println("HISTORY");
        System.err.println(history);
        boolean inHistory = history.contains(filelist[i].getCanonicalPath());
        history.add(filelist[i].getCanonicalPath());
        if (inHistory) {
            // skip it
        } else if (filelist[i].isDirectory()) {
            foldersize += getFileSize(filelist[i], history);
        } else {
            foldersize += filelist[i].length();
        }
    }
    return foldersize;
}

答案 4 :(得分:2)

迭代文件夹中的所有子文件夹,并获取所有文件的摘要大小。

答案 5 :(得分:0)

文件夹通常具有非常小的“大小”,您可以将它们视为索引。

所有返回文件夹“大小”的程序实际上都会迭代并累加文件的大小。

答案 6 :(得分:0)

import resource
import glob
import gc
rsrc = resource.RLIMIT_DATA
soft, hard = resource.getrlimit(rsrc)
print ('Soft limit starts as  :', soft)

resource.setrlimit(rsrc, (4 * 1024 * 1024 * 1024, hard))  # limit to four giga bytes

soft, hard = resource.getrlimit(rsrc)
print ('Soft limit changed to :', soft)

from keras.models import Sequential
import keras.optimizers
from keras.layers import Dense, Dropout, Activation, Flatten, BatchNormalization
from keras.layers import Convolution2D, MaxPooling2D,AveragePooling2D
import numpy as np
import random
from keras.utils import plot_model

sample_size = 1
batch_size = 50
input_shape = (int(720 / 4), int(1280 / 4), sample_size * 5)

# model
model = Sequential()
model.add(BatchNormalization(input_shape=input_shape))
model.add(Convolution2D(128, (3, 3), activation='relu', dim_ordering="tf", padding="same",kernel_initializer='random_uniform'))
model.add(Convolution2D(128, (3, 3), activation='sigmoid', dim_ordering="tf", padding="same",kernel_initializer='random_uniform'))

model.add(AveragePooling2D(pool_size=(4, 4), dim_ordering="tf"))
model.add(Convolution2D(256, (3, 3), activation='sigmoid', dim_ordering="tf", padding="same",kernel_initializer='random_uniform'))
model.add(Convolution2D(256, (3, 3), activation='sigmoid', dim_ordering="tf", padding="same",kernel_initializer='random_uniform'))

model.add(AveragePooling2D(pool_size=(4, 4), dim_ordering="tf"))

model.add(Convolution2D(512, (3, 3), activation='sigmoid', dim_ordering="tf", padding="same",kernel_initializer='random_uniform'))
model.add(Convolution2D(512, (3, 3), activation='sigmoid', dim_ordering="tf", padding="same",kernel_initializer='random_uniform'))

model.add(AveragePooling2D(pool_size=(4, 4), dim_ordering="tf"))

model.add(Flatten())
model.add(Dense(4096, activation='relu',kernel_initializer='random_uniform'))
#model.add(Dropout(0.5))
model.add(Dense(512, activation='sigmoid',kernel_initializer='random_uniform'))
model.add(Dense(1, activation='sigmoid',kernel_initializer='random_uniform'))
model.compile(loss='mean_absolute_error',
              optimizer='adam',
              metrics=['mae','mse'])
model.summary()
plot_model(model,to_file='model.png')

def generate_tr(batch_size, is_training=False):
    x=np.linspace(0, 10, num=5000).reshape(-1, 1)

    counter = 0
    print 'start'
    while 1:
        samples=np.zeros((batch_size, 720/4, 1280/4, 5))
        labels=[]
    for t in range (batch_size):
        i = int(random.randint(0, 4999))
        for b in range(sample_size): 
            samples[t, :,:,b*5:b*5+5] = np.random.rand(720/4,1280/4,5)/10+x[i] 

        labels.append((2*x[i])/100)

        counter += 1
        print counter #, labels
        yield ((samples), np.asarray(labels))


tt = model.fit_generator(generate_tr(batch_size, True), steps_per_epoch=100, epochs=10,
                         use_multiprocessing=False, verbose=2)

score = model.predict_generator(generate_tr(batch_size, True), steps=30)

}

答案 7 :(得分:0)

逐个文件浏览文件夹,获取每个文件的大小并将其添加到可变大小。

static int size=0;

 public static int folderSize(File folder){

    size = 0;

    File[] fileList = folder.listFiles();

    for(File file : fileList){
        if(!file.isFile()){ 
            folderSize(file);
        }
        size += file.length();
    }
    return size;
}