今天由于服务器配置管理那边需要一个批处理程序,需要实现的功能是: 能把本地的任意目录的子文件及子文件夹拷贝到指定的目标目录生成的350个文件夹当中去.350个文件夹也是动态生成的,象征性的用user1、user2、user3.......user350.
我是用多线程去实现的,每一个线程完成一份拷贝,那么就的new一个继承了Thread类的数组,数组的大小是350,这个类的run方法去调用要实现拷贝功能类的方法。值得一提的是这个线程类的350个实例都有自己的属性,并且这个类是immutable的。
那么好,我们来看看这个immutable类:
java 代码
- import java.io.File;
- class SimulateThread extends Thread
- {
- File root = null; //要拷贝的文件目录。
- String folder = null; //用来做user1、user2、.....的文件夹名称。
- File toFile=null; //目标目录。
- public SimulateThread(ThreadGroup threadgroup, File file,File toFile, String string) { //用构造函数给属性负值
- super(threadgroup, string);
- ((SimulateThread) this).root = file;
- ((SimulateThread) this).toFile=toFile;
- ((SimulateThread) this).folder = string;
- }
- public synchronized void start() {
- super.start();
- }
- public void run() {
- super.run();
- try {
- System.out.println(new StringBuilder().append
- (((SimulateThread) this).folder).append
- (" Executing...").toString());
- FileConverter.convertMultiFiles(((SimulateThread) this).root,((SimulateThread) this).toFile,
- ((SimulateThread) this).folder,
- "EUC-KR", "UTF-8");//调用用来生成的文件的方法,并把字符转换的编码格式传入,这里是把EUC-KR转为UTF-8
- System.out.println(new StringBuilder().append
- (((SimulateThread) this).folder).append
- (" Done.").toString());
- } catch (Exception exception) {
- exception.printStackTrace();
- }
- }
- }
哦,对了,看到StringBuilder这个东东,我的说一下编译及运行环境,必须是jdk5.0以上的版本才行,它是新类。说句题外话,C#里边也有这个东西,不知道是java借鉴C#呢,还是C#借鉴java的呢,对了还有泛型。反正这种情况的出现是一种好兆头。
言归正传,我们来看看FileConverter类,也是程序的主类,程序的入口在它这边
java 代码
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Vector;
- public class FileConverter {
- public static final int BUFFER_SIZE = 1024;
- public static final int EOF = -1;
- public static final int EOL = -1;
- public static final String BACK_SLASH = "\\";
- public static final String REG_BACK_SLASH = "\\\\";
- public static final String NEW_LINE_WINDOWS = "\r\n";
- public static final String NEW_LINE_UNIX = "\n";
- public static final String NEW_LINE_MACOS = "\r";
- public static OutputStreamWriter writer = null;
- public static final int SIMULATE_COUNT = 30;
- public static final String DEFAULT_FROM_ENCODING = "EUC-KR";
- public static final String DEFAULT_TO_ENCODING = "UTF-8";
- public static final String DEFAULT_SOURCE_PATH = "C:\\TEMP";
- private String from = "EUC-KR";
- private String to = "UTF-8";
- private String path = "C:\\TEMP";
- private String topath="C:\\TEMP1";
- public String getTopath() {
- return topath;
- }
- public void setTopath(String topath) {
- this.topath = topath;
- }
- public String getFrom() {
- return from;
- }
- public void setFrom(String string) {
- from = string;
- }
- public String getTo() {
- return to;
- }
- public void setTo(String string) {
- to = string;
- }
- public String getPath() {
- return path;
- }
- public void setPath(String string) {
- path = string;
- }
- public static void convertFile(String string, String string_0_,
- String string_1_, String string_2_) throws Exception { //实现单个文件的拷贝
- InputStreamReader inputstreamreader = new InputStreamReader(
- new FileInputStream(string), string_0_);
- File file = new File(string_1_);
- if (!file.getParentFile().exists())
- file.getParentFile().mkdirs();
- if (!file.exists())
- file.createNewFile();
- OutputStreamWriter outputstreamwriter = new OutputStreamWriter(
- new FileOutputStream(string_1_), string_2_);
- char[] cs = new char[1024];
- int i = -1;
- while ((i = inputstreamreader.read(cs)) != -1) {
- outputstreamwriter.write(cs, 0, i);
- outputstreamwriter.flush();
- }
- outputstreamwriter.close();
- }
- public static void listFiles(File file,
- OutputStreamWriter outputstreamwriter) throws Exception {
- if (file.isDirectory() && file.listFiles() != null) {
- File[] files = file.listFiles();
- for (int i = 0; i < files.length; i++) {
- File file_3_ = new File(files[i].getAbsolutePath());
- if (file_3_.isDirectory())
- listFiles(file_3_, outputstreamwriter);
- else if (file_3_.isFile()) {
- outputstreamwriter.write(new StringBuilder().append(
- file_3_.getAbsolutePath()).append("\r\n")
- .toString());
- outputstreamwriter.flush();
- } else
- System.out.println("What's this?");
- }
- }
- }
- public static Vector listSubFile(File file) throws Exception { //遍历源文件的目录及字文件夹,这种遍历本来可以写一个Composite Pattern来实现,时间比较紧,我就没做
- Vector vector = new Vector();
- if (file.isDirectory() && file.listFiles() != null) {
- File[] files = file.listFiles();
- for (int i = 0; i < files.length; i++) {
- File file_4_ = new File(files[i].getAbsolutePath());
- if (file_4_.isDirectory())
- vector.addAll(listSubFile(file_4_));
- else if (file_4_.isFile())
- vector.add(file_4_.getAbsolutePath());
- else
- System.out.println("What's this?");
- }
- }
- return vector;
- }
- public static HashMap restoreFiles(File file,File toFile, String string)
- throws Exception { //把源文件的目录作为key值,把目标目录+useri+以后文件目录或文件的名字做为value放到HashMap中
- HashMap hashmap = new HashMap();
- Vector vector = listSubFile(file);
- Iterator iterator = vector.iterator();
- while (iterator.hasNext()) {
- String string_5_ = (String) iterator.next();
- String string_6_ = doubleBackSlash(file.getAbsolutePath());
- String string_7_ = doubleBackSlash(toFile.getAbsolutePath());
- string_7_ = string_7_.concat("\\\\").concat(string);
- hashmap
- .put(string_5_, string_5_
- .replaceFirst(string_6_, string_7_));
- }
- return hashmap;
- }
- public static void convertMultiFiles(File file, File toFile,String string,
- String string_8_, String string_9_) throws Exception { //执行拷贝了
- HashMap hashmap = restoreFiles(file,toFile,string);
- Iterator iterator = hashmap.keySet().iterator();
- while (iterator.hasNext()) {
- String string_10_ = (String) iterator.next();
- convertFile(string_10_, string_8_,
- (String) hashmap.get(string_10_), string_9_);
- }
- }
- public static void setWriter() throws Exception {
- writer = new OutputStreamWriter(new FileOutputStream(
- "D:\\temp.tree.txt"), "GBK");
- }
- public static void closeWriter() throws Exception {
- writer.close();
- }
- public static String doubleBackSlash(String string) {
- StringBuffer stringbuffer = new StringBuffer(string);
- int i = -1;
- while ((i = stringbuffer.indexOf("\\", ++i)) != -1)
- stringbuffer.insert(++i, "\\");
- return stringbuffer.toString();
- }
- public static boolean checkCRLF(String string, String string_11_) {
- boolean bool = false;
- if (string != null && string.length() >= string_11_.length()
- && string.lastIndexOf(string_11_) != -1)
- bool = true;
- return bool;
- }
- public static String trailingTrim(String string, String string_12_) {
- if (string != null && string.length() >= string_12_.length())
- string = string.substring(0, string.indexOf(string_12_));
- return string;
- }
- public FileConverter() {
- path = "C:\\TEMP";
- }
- public void inputPath() {//获取System.in的输入,去掉回车符,并把要copy的目录与目标目录用空格分开
- String s = "";
- InputStreamReader inputstreamreader = new InputStreamReader(System.in);
- BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
- System.out.println("Unix: ctrl-d or ctrl-c to exit.\nWindows:Type ctrl-z or ctrl-c to exit.\nPlease " +
- "input source path:"
- );
- try
- {
- int i = bufferedreader.read();
- do
- {
- s = (new StringBuilder()).append(s).append((char)i).toString();
- if(i == 10 && checkCRLF(s, "\r\n"))
- {
- s = trailingTrim(s, "\r\n");
- if(s.length() == 0)
- {
- System.out.print("The default path: C:\\temp will be used for source path.");
- }
- break;
- }
- i = bufferedreader.read();
- } while(true);
- System.out.println((new StringBuilder()).append("Read: ").append(s).toString());
- bufferedreader.close();
- }
- catch(IOException ioexception)
- {
- ioexception.printStackTrace();
- }
- String[] temp=s.split(" ");
- setPath(temp[0]);//set copy的目录
- this.setTopath(temp[1]);//set 目标目录
- File toFile=new File(topath);
- toFile.mkdir();//生成目标目录。
- }
- public void start() throws Exception {
- inputPath();
- String[] strings = new String[350];
- for (int i = 0; i < strings.length; i++)
- strings[i] = new StringBuilder().append("user").append(i + 1)
- .toString();
- File file = new File(path);
- File toFile=new File(topath);
- ThreadGroup threadgroup = new ThreadGroup("APP TEST");
- Thread[] threads = new Thread[350];
- for (int i = 0; i < threads.length; i++) {//生成350个SimulateThread对象并把在目标目录生成的文件夹的名称也作为参数
- threads[i] = new SimulateThread(threadgroup, file,toFile, strings[i]);
- threads[i].start();
- }
- for (;;) {
- int i = threadgroup.activeCount();
- if (i <= 0)
- break;
- Thread.sleep(500L);
- }
- System.out.println("Done.");
- }
- public static void main(String[] strings) throws Exception {
- new FileConverter().start();//创建一个FileConverter对象并且调用它的start方法
- }
- }
好了,破于时间注释也不多写了,以上的代码大多都能看懂,俺也不多说了.
可以把他们的class文件打成jar文件,在 manifest.MF 写上Main-Class: FileConverter再写一个批处理run.bat
java -jar jar包名
噢了。。。。。。。。。。。。。。。。。。