总是发现自己的C盘快满了,清理程序也不会帮我自己清理,然后就自己写了一个程序去读取磁盘下的目录占多大空间,目前只能读取总的大小,正在整改看能不能把每个目录总的大小打印出来,这样就可以去删除了,否则自己挨个的去看,岂不是很傻,毕竟自己也是个屌丝程序员啊。
下面的都是从网上摘录下的,我拿的这几个都能跑,不能跑的,我就不贴出来了。
方法一:
package com.beijishiqidu.file; import java.io.File; public class _01_TotalFileSizeSequential { public static void main(String[] args) { final long start = System.nanoTime(); String filePath = "C:\\Users\\Administrator"; File file = new File(filePath); Long result = getTotalFileSize(file); final long end = System.nanoTime(); System.out.println("总大小为(G):" + result / 1024d / 1024d / 1024d); System.out.println("_01_TotalFileSizeSequential ----> Time taken(秒): " + (end - start) / 1.0e9); } private static long getTotalFileSize(File file) { if (file.isFile()) { return file.length(); } File[] fileArray = file.listFiles(); long total = 0; if (fileArray != null) { for (File tmpFile : fileArray) { total += getTotalFileSize(tmpFile); } } return total; } }
运行结果:
总大小为(G):8.57133452873677 _01_TotalFileSizeSequential ----> Time taken(秒): 11.744519825
方法二:
package com.beijishiqidu.file; 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.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; public class _02_ConcurrentTotalFileSize { public static void main(String[] args) { final long start = System.nanoTime(); String filePath = "C:\\Users\\Administrator"; File file = new File(filePath); Long result = new _02_ConcurrentTotalFileSize().getTotalSizeOfFilesInDir(file); final long end = System.nanoTime(); System.out.println("总大小为(G):" + result / 1024d / 1024d / 1024d); System.out.println("_02_ConcurrentTotalFileSize ----> Time taken(秒): " + (end - start) / 1.0e9); } 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) { final ExecutorService service = Executors.newFixedThreadPool(100); long total = 0; try { 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; } } } catch (Exception e) { e.printStackTrace(); } finally { service.shutdown(); } return total; } }
运行结果:
总大小为(G):8.571664821356535 _02_ConcurrentTotalFileSize ----> Time taken(秒): 7.665382601
方法三:
package com.beijishiqidu.file; 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 _04_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 void main(String[] args) throws Exception { final long start = System.nanoTime(); String filePath = "C:\\Users\\Administrator"; File file = new File(filePath); Long result = new _04_ConcurrentTotalFileSizeWLatch().getTotalSizeOfFile(file); final long end = System.nanoTime(); System.out.println("总大小为(G):" + result / 1024d / 1024d / 1024d); System.out.println("_04_ConcurrentTotalFileSizeWLatch ----> Time taken(秒): " + (end - start) / 1.0e9); } 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 File file) throws InterruptedException { service = Executors.newFixedThreadPool(100); pendingFileVisits.incrementAndGet(); try { updateTotalSizeOfFilesInDir(file); latch.await(100, TimeUnit.SECONDS); return totalSize.longValue(); } finally { service.shutdown(); } } }
运行结果:
总大小为(G):8.572077584452927 _04_ConcurrentTotalFileSizeWLatch ----> Time taken(秒): 7.384791101
方法四:
package com.beijishiqidu.file; 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 _05_ConcurrentTotalFileSizeWQueue { private ExecutorService service; final private BlockingQueue<Long> fileSizes = new ArrayBlockingQueue<Long>(500); final AtomicLong pendingFileVisits = new AtomicLong(); public static void main(String[] args) throws Exception { final long start = System.nanoTime(); String filePath = "C:\\Users\\Administrator"; File file = new File(filePath); Long result = new _05_ConcurrentTotalFileSizeWQueue().getTotalSizeOfFile(file); final long end = System.nanoTime(); System.out.println("总大小为(G):" + result / 1024d / 1024d / 1024d); System.out.println("_05_ConcurrentTotalFileSizeWQueue ----> Time taken(秒): " + (end - start) / 1.0e9); } 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 File file) throws InterruptedException { service = Executors.newFixedThreadPool(100); try { startExploreDir(file); 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(); } } }
运行结果:
总大小为(G):8.572272757068276 _05_ConcurrentTotalFileSizeWQueue ----> Time taken(秒): 7.623957758
方法五:
package com.beijishiqidu.file; 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 _06_FileSizeWForkJoinPool { public static void main(String[] args) { final long start = System.nanoTime(); String filePath = "C:\\Users\\Administrator"; File file = new File(filePath); ForkJoinPool forkJoinPool = new ForkJoinPool(); Long result = forkJoinPool.invoke(new FileSizeFinder(file)); final long end = System.nanoTime(); System.out.println("总大小为(G):" + result / 1024d / 1024d / 1024d); System.out.println("_06_FileSizeWForkJoinPool ----> Time taken(秒): " + (end - start) / 1.0e9); } private static class FileSizeFinder extends RecursiveTask<Long> { private static final long serialVersionUID = 8030791942789701702L; 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; } } }
运行结果:
总大小为(G):8.572774960659444 _06_FileSizeWForkJoinPool ----> Time taken(秒): 5.658299909
相关推荐
以下是对几种主要Java读取外部资源方法的详细解释和实例代码。 1. **从当前工作目录读取** 当资源文件位于程序运行时的工作目录下时,可以使用`FileInputStream`来读取。例如: ```java try { BufferedReader ...
本文将通过实例代码展示如何结合这两种技术来达到上述功能,并将着重介绍以下几个核心知识点: 1. Java NIO简介 Java NIO是一种基于通道(Channel)和缓冲区(Buffer)的I/O操作方法,相比传统的基于流的I/O操作...
2. **初始化串口**:使用RXTX库,你可以通过`SerialPort`类获取到一个串口实例,如`CommPortIdentifier.getPortIdentifiers()`方法可以列出所有可用的串口。然后,使用`SerialPort.getSerialPort()`获取特定的串口。...
实例150 实例化Class类的5种方式 196 实例151 获得Class对象表示实体的名称 197 实例152 查看类的声明 198 实例153 查看类的成员 199 实例154 按继承层次对类排序 201 实例155 查看内部类信息 202 7.2 反射的进阶 ...
本实例聚焦于JAVA与倍福(Beckhoff)的TC2(Twincat 2)之间的通信,这是一种用于实现计算机与控制器之间PLC变量交互的方式。下面将详细介绍这个主题,并围绕提供的文件进行解析。 首先,我们要理解JAVA与倍福TC2...
在IT行业中,电子邮件通信是日常工作中不可或缺的一部分,而Java作为一种广泛应用的编程语言,提供了多种方式来处理邮件的发送和接收。本示例着重讲解如何利用Java结合Microsoft的Exchange协议实现邮件功能,具体...
创建一个 Document 实例并使用 Document.loadFromFile() 方法加载一个示例 Word 文档。创建一个 StringBuilder 对象,然后使用 StringBuilder.append() 方法记录数据。遍历所有 Section 和 section 中 body 下的每一...
Java电子相册是一种基于Java编程语言开发的软件应用,它允许用户存储、管理和查看他们的照片。这个特定的电子相册项目显然设计得简洁易用,用户只需点击相册的名称,就能预览其中包含的照片。对于正在学习Java编程,...
在SWFUpload的实现中,关键文件包括以下几个部分: 1. **核心文件**:`SWFUpload`文件夹包含了所有必要的文件,如Flash对象(`swfupload.swf`)、JavaScript库(`swfupload.js`、`swfupload.queue.js`等)以及样式...
首先,Java作为一种多平台支持的编程语言,其跨平台特性使得开发的条形码应用可以在各种操作系统上运行,包括Windows、Linux和Mac OS等。此项目可能采用了Java的标准库和第三方库来实现条形码的读取与解析。 在提供...
5. **使用示例**:在Java代码中,你可以创建一个`Tesseract`实例,指定图像路径,选择识别的语言,然后调用`Recognize()`方法进行识别。例如: ```java File imageFile = new File("path_to_your_image.png"); ...
这是一个基于Java语言开发的B2B(Business-to-Business)行业网站电子商务系统的源代码实例。在深入探讨这个系统之前,我们需要了解几个关键概念。 首先,Java是一种广泛使用的面向对象的编程语言,以其“一次编写...
在"PullParseXml"这个示例中,开发者可能创建了一个名为"PullParseXml.java"的类,该类包含了一个方法,专门用来从assets目录下的XML文件中提取数据。这个方法可能接受XML文件名作为参数,然后使用上述步骤进行解析...
8. **文件操作**:游戏可能需要保存和读取用户数据,如得分、等级等,这时就需要用到Java的File类和流对象进行文件的读写操作。 9. **音效和图像处理**:Java的 AudioClip 类可以播放音频,而JavaFX或第三方库如...
- **8种基本数据类型及其字节数**:Java提供了八种基本数据类型,包括四种整型(`byte`、`short`、`int`、`long`)、两种浮点型(`float`、`double`)、一种字符型(`char`)和一种布尔型(`boolean`)。每种类型都...