public class TotalFileSizeSequential{
private long getTotalSizeOfFileInDir(final File file){
if(file.isFile()){
return file.length();
}
final File[] children = file.listFile();
if(children!=null){
for(final File child:children){
total += getTotalSizeOfFileInDir(child);//递归遍历
}
}
return total
}
public void static main(String[] args){
Scanner scanner = new Scanner(System.in);
String str = scanner.next(); //输入目录
final long start = System.nanoTime();
final long total = new TotalFileSizeSequential().getTotalSizeOfFilesInDir(new File(str));
final long end = System.nanoTime();
System.out.println("文件总大小 " + total);
System.out.println("所用时间 " + (end-start)/1.0e9);
}
}public class NavelyConcurrentTotalFileSize{
private long getTotalSizeOfFileInDir(ExecutorService service,File file)
throws InterruptedException,ExecutionException,TimeoutException{
if(file.isFile()){
return file.length();
}
long total = 0;
final File[] children = file.listFile();
if(children != null){
final List<Future<Long>> partialTotalFuture = new ArrayList<Future<Long>>();
for(final File child:children){
partialTotalFuture.add(service.submit(new Callable<Long>{ //执行任务
public Long call() throws InterruptedException,
ExecutionException,TimeoutException{
return getTotalSizeOfFilesInDir(service,child);
}
}));
}
for(Future<Long> partialTotalFuture:partialTotalFutures){
total += partialTotalFuture.get(100,TimeUnit.SECODES);//计算结果
}
}
return tatal;
}
private long getTotalSizeOfFile(string fileName) throws InterruptedException,
ExecutionException,TimeoutException{
ExecutorService service = Executors.newFixedThreadPool(100);
try{
return getTotalSizeOfFileInDir(service,new File(fileName));
}finally{
service.shutdown();
}
}
public void static main(String[] args){
Scanner scanner = new Scanner(System.in);
String str = scanner.next(); //输入目录
final long start = System.nanoTime();
final long total = new NaivelyConcurrentTotalFileSize().getTotalSizeOfFile(str);
final long end = System.nanoTime();
System.out.println("文件总大小 " + total);
System.out.println("所用时间 " + (end-start)/1.0e9);
}
}| 欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |