JAVA读取文件夹大小的几种方法实例

(一)单线程递归方式

代码如下:

package com.taobao.test;

import java.io.File;

public class TotalFileSizeSequential {

public static String fileName = "C:\\Documents and Settings\\Administrator\\桌面\\monkeytalk";

// 递归方式 计算文件的大小
    private long getTotalSizeOfFilesInDir(final File file) {
        if (file.isFile())
            return file.length();
        final File[] children = file.listFiles();
        long total = 0;
        if (children != null)
            for (final File child : children)
                total += getTotalSizeOfFilesInDir(child);
        return total;
    }

public static void main(final String[] args) {
        final long start = System.nanoTime();

final long total = new TotalFileSizeSequential()
                .getTotalSizeOfFilesInDir(new File(fileName));
        final long end = System.nanoTime();
        System.out.println("Total Size: " + total);
        System.out.println("Time taken: " + (end - start) / 1.0e9);
    }
}

(二)使用Executors.newFixedThreadPool和callable 多线程实现

代码如下:

package com.taobao.test;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ConcurrentTotalFileSize {

public static final String fileName = "C:\\Documents and Settings\\Administrator\\桌面\\monkeytalk";

class SubDirectoriesAndSize {

final public long size;
        final public List<File> subDirectories;

public SubDirectoriesAndSize(final long totalSize,
                final List<File> theSubDirs) {
            size = totalSize;
            subDirectories = Collections.unmodifiableList(theSubDirs);
        }
    }

private SubDirectoriesAndSize getTotalAndSubDirs(final File file) {
        long total = 0;
        final List<File> subDirectories = new ArrayList<File>();
        if (file.isDirectory()) {
            final File[] children = file.listFiles();
            if (children != null)
                for (final File child : children) {
                    if (child.isFile())
                        total += child.length();
                    else
                        subDirectories.add(child);
                }
        }
        return new SubDirectoriesAndSize(total, subDirectories);
    }

private long getTotalSizeOfFilesInDir(final File file)
            throws InterruptedException, ExecutionException, TimeoutException {
        final ExecutorService service = Executors.newFixedThreadPool(100);
        try {
            long total = 0;
            final List<File> directories = new ArrayList<File>();
            directories.add(file);
            while (!directories.isEmpty()) {
                final List<Future<SubDirectoriesAndSize>> partialResults = new ArrayList<Future<SubDirectoriesAndSize>>();
                for (final File directory : directories) {
                    partialResults.add(service
                            .submit(new Callable<SubDirectoriesAndSize>() {
                                public SubDirectoriesAndSize call() {
                                    return getTotalAndSubDirs(directory);
                                }
                            }));
                }
                directories.clear();
                for (final Future<SubDirectoriesAndSize> partialResultFuture : partialResults) {
                    final SubDirectoriesAndSize subDirectoriesAndSize = partialResultFuture
                            .get(100, TimeUnit.SECONDS);
                    directories.addAll(subDirectoriesAndSize.subDirectories);
                    total += subDirectoriesAndSize.size;
                }
            }
            return total;
        } finally {
            service.shutdown();
        }
    }

public static void main(final String[] args) throws InterruptedException,
            ExecutionException, TimeoutException {
        final long start = System.nanoTime();
        final long total = new ConcurrentTotalFileSize()
                .getTotalSizeOfFilesInDir(new File(fileName));
        final long end = System.nanoTime();
        System.out.println("Total Size: " + total);
        System.out.println("Time taken: " + (end - start) / 1.0e9);
    }
}

(三)使用Executors.newFixedThreadPool和callable 多线程的另外一种实现

代码如下:

package com.taobao.test;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class NaivelyConcurrentTotalFileSize {
    public static String fileName = "C:\\Documents and Settings\\Administrator\\桌面\\monkeytalk";

private long getTotalSizeOfFilesInDir(final ExecutorService service,
            final File file) throws InterruptedException, ExecutionException,
            TimeoutException {
        if (file.isFile())
            return file.length();

long total = 0;
        final File[] children = file.listFiles();

if (children != null) {
            final List<Future<Long>> partialTotalFutures = new ArrayList<Future<Long>>();
            for (final File child : children) {
                partialTotalFutures.add(service.submit(new Callable<Long>() {
                    public Long call() throws InterruptedException,
                            ExecutionException, TimeoutException {
                        return getTotalSizeOfFilesInDir(service, child);
                    }
                }));
            }

for (final Future<Long> partialTotalFuture : partialTotalFutures)
                total += partialTotalFuture.get(100, TimeUnit.SECONDS);

}

return total;

}

private long getTotalSizeOfFile(final String fileName)
            throws InterruptedException, ExecutionException, TimeoutException {
        final ExecutorService service = Executors.newFixedThreadPool(100);
        try {
            return getTotalSizeOfFilesInDir(service, new File(fileName));
        } finally {
            service.shutdown();
        }
    }

public static void main(final String[] args) throws InterruptedException,
            ExecutionException, TimeoutException {
        final long start = System.nanoTime();
        final long total = new NaivelyConcurrentTotalFileSize()
                .getTotalSizeOfFile(fileName);
        final long end = System.nanoTime();
        System.out.println("Total Size: " + total);
        System.out.println("Time taken: " + (end - start) / 1.0e9);
    }
}

(四)使用CountDownLatch和AtomicLong实现多线程下的并发控制

代码如下:

package com.taobao.test;

import java.io.File;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

public class ConcurrentTotalFileSizeWLatch {
    private ExecutorService service;
    final private AtomicLong pendingFileVisits = new AtomicLong();
    final private AtomicLong totalSize = new AtomicLong();
    final private CountDownLatch latch = new CountDownLatch(1);
    public static String fileName = "C:\\Documents and Settings\\Administrator\\桌面\\monkeytalk";

private void updateTotalSizeOfFilesInDir(final File file) {
        long fileSize = 0;
        if (file.isFile())
            fileSize = file.length();
        else {
            final File[] children = file.listFiles();
            if (children != null) {
                for (final File child : children) {
                    if (child.isFile())
                        fileSize += child.length();
                    else {
                        pendingFileVisits.incrementAndGet();
                        service.execute(new Runnable() {
                            public void run() {
                                updateTotalSizeOfFilesInDir(child);
                            }
                        });
                    }
                }
            }
        }
        totalSize.addAndGet(fileSize);
        if (pendingFileVisits.decrementAndGet() == 0)
            latch.countDown();
    }

private long getTotalSizeOfFile(final String fileName)
            throws InterruptedException {
        service = Executors.newFixedThreadPool(100);
        pendingFileVisits.incrementAndGet();
        try {
            updateTotalSizeOfFilesInDir(new File(fileName));
            latch.await(100, TimeUnit.SECONDS);
            return totalSize.longValue();
        } finally {
            service.shutdown();
        }
    }

public static void main(final String[] args) throws InterruptedException {
        final long start = System.nanoTime();
        final long total = new ConcurrentTotalFileSizeWLatch()
                .getTotalSizeOfFile(fileName);
        final long end = System.nanoTime();
        System.out.println("Total Size: " + total);
        System.out.println("Time taken: " + (end - start) / 1.0e9);
    }
}

(五)使用BlockingQueue和AtomicLong的实现

代码如下:

package com.taobao.test;

import java.io.File;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

public class ConcurrentTotalFileSizeWQueue {
    public static String fileName = "C:\\Documents and Settings\\Administrator\\桌面\\monkeytalk";

private ExecutorService service;
    final private BlockingQueue<Long> fileSizes = new ArrayBlockingQueue<Long>(
            500);
    final AtomicLong pendingFileVisits = new AtomicLong();

private void startExploreDir(final File file) {
        pendingFileVisits.incrementAndGet();
        service.execute(new Runnable() {
            public void run() {
                exploreDir(file);
            }
        });
    }

private void exploreDir(final File file) {
        long fileSize = 0;
        if (file.isFile())
            fileSize = file.length();
        else {
            final File[] children = file.listFiles();
            if (children != null)
                for (final File child : children) {
                    if (child.isFile())
                        fileSize += child.length();
                    else {
                        startExploreDir(child);
                    }
                }
        }
        try {
            fileSizes.put(fileSize);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
        pendingFileVisits.decrementAndGet();
    }

private long getTotalSizeOfFile(final String fileName)
            throws InterruptedException {
        service = Executors.newFixedThreadPool(100);
        try {
            startExploreDir(new File(fileName));
            long totalSize = 0;
            while (pendingFileVisits.get() > 0 || fileSizes.size() > 0) {
                final Long size = fileSizes.poll(10, TimeUnit.SECONDS);
                totalSize += size;
            }
            return totalSize;
        } finally {
            service.shutdown();
        }
    }

public static void main(final String[] args) throws InterruptedException {
        final long start = System.nanoTime();
        final long total = new ConcurrentTotalFileSizeWQueue()
                .getTotalSizeOfFile(fileName);
        final long end = System.nanoTime();
        System.out.println("Total Size: " + total);
        System.out.println("Time taken: " + (end - start) / 1.0e9);
    }
}

(六)使用jdk7的ForkJoin来实现

代码如下:

package com.taobao.test;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class FileSize {
    private final static ForkJoinPool forkJoinPool = new ForkJoinPool();
    public static String fileName = "C:\\Documents and Settings\\Administrator\\桌面\\monkeytalk";

private static class FileSizeFinder extends RecursiveTask<Long> {
        final File file;

public FileSizeFinder(final File theFile) {
            file = theFile;
        }

@Override
        public Long compute() {
            long size = 0;
            if (file.isFile()) {
                size = file.length();
            } else {
                final File[] children = file.listFiles();
                if (children != null) {
                    List<ForkJoinTask<Long>> tasks = new ArrayList<ForkJoinTask<Long>>();
                    for (final File child : children) {
                        if (child.isFile()) {
                            size += child.length();
                        } else {
                            tasks.add(new FileSizeFinder(child));
                        }
                    }
                    for (final ForkJoinTask<Long> task : invokeAll(tasks)) {
                        size += task.join();
                    }
                }
            }
            return size;
        }
    }

public static void main(final String[] args) {
        final long start = System.nanoTime();
        final long total = forkJoinPool.invoke(new FileSizeFinder(new File("/home")));
        final long end = System.nanoTime();
        System.out.println("Total Size: " + total);
        System.out.println("Time taken: " + (end - start) / 1.0e9);
    }
}

(0)

相关推荐

  • 用Java将字符串的首字母转换大小写

    话不多说,直接上代码 //首字母转小写 public static String toLowerCaseFirstOne(String s){ if(Character.isLowerCase(s.charAt(0))) return s; else return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString(); } //首字母转大写 public

  • Java字母加数字组合比较大小

    针对字符串是数字和字母结合而进行的,如"a20"和"a9";比较而得出结果是"a20">"a9".这种情况直接调用String的compareTo方法得出的结果是不是我们希望的.这个时候就需要写自己的类并且实现Comarable接口来进行比较.这个是来源一次的面试题目,但是当时只有个思路. 思路: 1.转换String为包含substring和Integer的list.(这里用String的spit方法直接拆分不知道怎么

  • Java字母大小写转换的方法

    案例: 要求从控制台接收用户输入的一个字母,如果这个字母是小写,转换为大写:如果这个字母是大写,转换为小写:只能输入字母,如果是其他值,提示数据有误! 实现代码: import java.util.Scanner; /** * 常见字母大小写转换 * 原理: * 字符char采用的是Unicode编码的16位字符类型,其表示范围是0-65536.标准的8位ASCII字符集是Unicode * 的子集,其取值范围为0-127.大小写字母之间正好相差32 * @author Administrati

  • Java 大小写最快转换方式实例代码

    Java 大小写最快转换方式实例代码          这里直接给出实现代码,在代码中注释都很清楚,不多做介绍. Java代码 package io.mycat; import java.util.stream.IntStream; /** * 小写字母的 'a'=97 大写字母 A=65 更好相差32利用这个差进行大小写转换 * @author : Hpgary * @date : 2017年5月3日 10:26:26 * @mail: hpgary@qq.com * */ public cl

  • Java金额大小写的转换方法

    本文实例为大家分享了Java金额大小写转换的具体代码,供大家参考,具体内容如下 /** * @ClassName: NumberConvert * @Description: TODO * @date 2013-3-07 下午16:08:10 * @version V1.0 */ public class MoneyUtil { /** 大写数字 */ private static final String[] NUMBERS = { "零", "壹", "

  • Java 随机生成验证码(支持大小写字母、数字、随机字体)的实例

    代码如下所示: 复制代码 代码如下: package com.hoo.util; import java.awt.Color;  import java.awt.Font;  import java.awt.Graphics;  import java.awt.image.BufferedImage;  import java.util.Random; import javax.imageio.ImageIO;  import javax.servlet.http.HttpServletRequ

  • java实现人民币大小写转换方法分享

    复制代码 代码如下: /**     * 人民币转成大写     *      * @param value     * @return String     */    public static String hangeToBig(double value)    {        char[] hunit = { '拾', '佰', '仟' }; // 段内位置表示        char[] vunit = { '万', '亿' }; // 段名表示        char[] digi

  • JAVA读取文件夹大小的几种方法实例

    (一)单线程递归方式 复制代码 代码如下: package com.taobao.test; import java.io.File; public class TotalFileSizeSequential { public static String fileName = "C:\\Documents and Settings\\Administrator\\桌面\\monkeytalk"; // 递归方式 计算文件的大小    private long getTotalSizeO

  • java读取文件内容为string字符串的方法

    直接就把项目中的方法贴出来吧 /** * 读出城市列表文件 */ private String readCityFile() { File file02 = new File(path_xinfu, "/cityList.json"); FileInputStream is = null; StringBuilder stringBuilder = null; try { if (file02.length() != 0) { /** * 文件有内容才去读文件 */ is = new

  • python3读取文件指定行的三种方法

    行遍历实现 在python中如果要将一个文件完全加载到内存中,通过file.readlines()即可,但是在文件占用较高时,我们是无法完整的将文件加载到内存中的,这时候就需要用到python的file.readline()进行迭代式的逐行读取: filename = 'hello.txt' with open(filename, 'r') as file: line = file.readline() counts = 1 while line: if counts >= 50000000:

  • java读取文件显示进度条的实现方法

    实现这个功能比较简单,用到的类有两个:ProgressMonitorInputStream(主要是整个类) 和 ProgressMonitor ,它们在javax.swing中大体思路,你要首先知道整个文件的大小,和当前已经读取文件的大小,获得整个文件大小的方法 复制代码 代码如下: ProgressMonitorInputStream monitor;/*** @param 表示此进度条要依附在哪个组件上* @param 显示在此进度条上的消息* @param 需要监控的输入流*/monito

  • Java实现文件上传的两种方法(uploadify和Spring)

    最近项目中用到的两种文件上传方式做一下总结: 一. uploadify: uploadify控件的scripts和styles在这里:图片上传 JSP: <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ include file="../jsp/include/taglibs.jsp"%> <!DOCTYPE HTML PUBL

  • C#实现Web文件上传的两种方法实例代码

    1. C#实现Web文件的上传 使用C#如何实现文件上传的功能呢?下面笔者简要介绍一下. 首先,在你的Visual C# web project 中增加一个上传用的Web Form,为了要上传文件,需要在ToolBox中选择HTML类的File Field控件,将此控件加入到Web Form中,然而此时该控件还不是服务端控件,我们需要为它加上如下一段代码:<input id=PreviousFile1 type=file size=49 runat="server">,这样

  • Android查看文件夹大小以及删除文件夹的工具类

    在开发中当程序发生ANR或者异常,我们会将信息存在本地,然后上传服务器,这样可以实时去发现问题修改问题. 那我们需要获取文件之后需要对文件进行删除等操作,下面是写的一个工具类,用于查看文件夹大小以及删除文件夹. import android.text.TextUtils; import java.io.File; import java.math.BigDecimal; public class StorageCleanUtils { /** * 获取文件夹大小(递归) * * @param f

  • Java读取文件及基于正则表达式的获取电话号码功能详解

    本文实例讲述了Java读取文件及基于正则表达式的获取电话号码功能.分享给大家供大家参考,具体如下: 1.正则表达式 正则表达式,又称 正规表示法 . 常规表示法 (英语:Regular Expression,在代码中常简写为regex.regexp或RE),计算机科学的一个概念.正则表达式使用单个字符串来描述.匹配一系列符合某个句法规则的字符串.在很多文本编辑器里,正则表达式通常被用来检索.替换那些符合某个模式的文本. 用到的一些特殊构造正则表达式的意义解析: ? 当该字符 紧跟在任何一个其他限

  • Java读取文件的简单实现方法

    本文实例讲述了Java读取文件的简单实现方法,非常实用.分享给大家供大家参考之用.具体方法如下: 这是一个简单的读取文件的代码,并试着读取一个log文件,再输出. 主要代码如下: import java.io.*; public class FileToString { public static String readFile(String fileName) { String output = ""; File file = new File(fileName); if(file.

  • python2.7读取文件夹下所有文件名称及内容的方法

    最近稍稍有点空闲时间,于是重新温习了一下之前学习过的python基础.废话不多说,记录一下自己的所得. 首先,安装什么的不在本人的温习范围,另,本人使用的是windows下的python2.7版本,且本人相对来说只是小白,各位看官勿喷哈. python,本身来说是一门高级编程语言,有句话怎么说来着,越是高级的程序越简单,这几句话在表面来说是正确的.python它入门简单,有基础的学起来很快就能有简单的应用,但是在非常高的抽象计算中,高级的python程序设计也是非常难学的.我之所以学它,单纯的是

随机推荐