search
HomeJavajavaTutorialHow to read folder size in 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>> partialResults = new ArrayList<future>>();                 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);     } }</subdirectoriesandsize></subdirectoriesandsize></future></future></file></file></file></file></file></file>

(三)使用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>> partialTotalFutures = new ArrayList<future>>();             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);     } }</long></long></future></future>

(四)使用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);     } }</long></long>

(六)使用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>> tasks = new ArrayList<forkjointask>>();                     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);     } }</long></forkjointask></forkjointask></long>

The above is the detailed content of How to read folder size in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),