熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java高級技術 >> 正文

用java線程實現批量修改文件名

2022-06-13   來源: Java高級技術 
    /**
   
    * this program TODO
   
    * @version
   
    * @ausor widjan wu
   
    */
   
    package file;
   
    import javaioFile;
   
    import javautilArrayList;
   
    import javautilScanner;
   
    import ncurrent*;
   
    public class ChangeFileName
   
    {
   
    public static void main(String[] args)
   
    {
   
    Scanner in = new Scanner(Systemin)
   
    Systemoutprint(Enter base directory :
   
    String directory = innextLine()
   
    Systemoutprint(Enter key words:
   
    String keywords = innextLine()
   
    ExecutorService pool = ExecutorsnewCachedThreadPool()
   
    ChangeName change = new ChangeName(new File(directory) keywords pool)
   
    Future<Integer> result = poolsubmit(change)
   
    try {
   
    Systemoutprintln(resultget() + files were changed
   
    } catch (ExecutionException e) {
   
    eprintStackTrace()
   
    } catch (InterruptedException e) {
   
    }
   
    poolshutdown()
   
    int largestPoolSize = ((ThreadPoolExecutor) pool)getLargestPoolSize()
   
    Systemoutprintln(largest pool size : + largestPoolSize)
   
    }
   
    }
   
    class ChangeName implements Callable<Integer>
   
    {
   
    public ChangeName(File directory String keywords ExecutorService pool) {
   
    thisdirectory = directory;
   
    thispool = pool;
   
    thiskeywords = keywords;
   
    }
   
    public Integer call()
   
    {
   
    count = ;
   
    try
   
    {
   
    File[] files = directorylistFiles()
   
    ArrayList<Future<Integer》 results = new ArrayList<Future<Integer》()
   
    for (File file : files) {
   
    if (fileisDirectory()) {
   
    ChangeName change = new ChangeName(file keywords pool)
   
    Future<Integer> result = poolsubmit(change)
   
    } else {
   
    count++;
   
    String path = filegetPath()
   
    int index = pathlastIndexOf(\\
   
    path = pathsubstring( index+
   
    Systemoutprintln(path)
   
    String oldName = filegetName()
   
    String fileType = oldNamesubstring(oldNamelastIndexOf())
   
    String newFName = path + keywords + count + fileType;
   
    filerenameTo(new File(newFName))
   
    }
   
    }
   
    for(Future<Integer> result:results)
   
    {
   
    try
   
    {
   
    count +=resultget()
   
    }catch(ExecutionException e)
   
    {
   
    eprintStackTrace()
   
    }
   
    }
   
    }catch(InterruptedException e)
   
    {
   
    }
   
    return count;
   
    }
   
    private File directory;
   
    private String keywords;
   
    private ExecutorService pool;
   
    private int count;
   
    }
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27511.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.