java

位置:IT落伍者 >> java >> 浏览文章

用java线程实现批量修改文件名


发布日期:2021年10月18日
 
用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;

}               

上一篇:java多线程中synchronized关键字的用法

下一篇:Java 线程的几种状态