`
qingyuan914
  • 浏览: 21672 次
  • 性别: Icon_minigender_1
  • 来自: 北京
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

实现文件及目录的拷贝.

阅读更多

今天由于服务器配置管理那边需要一个批处理程序,需要实现的功能是: 能把本地的任意目录的子文件及子文件夹拷贝到指定的目标目录生成的350个文件夹当中去.350个文件夹也是动态生成的,象征性的用user1、user2、user3.......user350.

我是用多线程去实现的,每一个线程完成一份拷贝,那么就的new一个继承了Thread类的数组,数组的大小是350,这个类的run方法去调用要实现拷贝功能类的方法。值得一提的是这个线程类的350个实例都有自己的属性,并且这个类是immutable的。

那么好,我们来看看这个immutable类:

java 代码
  1. import java.io.File;   
  2.   
  3. class SimulateThread extends Thread   
  4. {   
  5.     File root = null;    //要拷贝的文件目录。   
  6.     String folder = null;    //用来做user1、user2、.....的文件夹名称。   
  7.     File toFile=null;    //目标目录。       
  8.     public SimulateThread(ThreadGroup threadgroup, File file,File toFile, String string) { //用构造函数给属性负值   
  9.   
  10.     super(threadgroup, string);   
  11.     ((SimulateThread) this).root = file;   
  12.     ((SimulateThread) this).toFile=toFile;   
  13.     ((SimulateThread) this).folder = string;   
  14.     }   
  15.        
  16.     public synchronized void start() {   
  17.     super.start();   
  18.     }   
  19.        
  20.     public void run() {   
  21.     super.run();   
  22.     try {   
  23.         System.out.println(new StringBuilder().append   
  24.                    (((SimulateThread) this).folder).append   
  25.                    (" Executing...").toString());   
  26.         FileConverter.convertMultiFiles(((SimulateThread) this).root,((SimulateThread) this).toFile,   
  27.                         ((SimulateThread) this).folder,   
  28.                         "EUC-KR""UTF-8");//调用用来生成的文件的方法,并把字符转换的编码格式传入,这里是把EUC-KR转为UTF-8   
  29.         System.out.println(new StringBuilder().append   
  30.                    (((SimulateThread) this).folder).append   
  31.                    (" Done.").toString());   
  32.     } catch (Exception exception) {   
  33.         exception.printStackTrace();   
  34.     }   
  35.     }   
  36. }  
哦,对了,看到StringBuilder这个东东,我的说一下编译及运行环境,必须是jdk5.0以上的版本才行,它是新类。说句题外话,C#里边也有这个东西,不知道是java借鉴C#呢,还是C#借鉴java的呢,对了还有泛型。反正这种情况的出现是一种好兆头。

言归正传,我们来看看FileConverter类,也是程序的主类,程序的入口在它这边

java 代码
  1. import java.io.BufferedReader;   
  2. import java.io.File;   
  3. import java.io.FileInputStream;   
  4. import java.io.FileOutputStream;   
  5. import java.io.IOException;   
  6. import java.io.InputStreamReader;   
  7. import java.io.OutputStreamWriter;   
  8. import java.util.HashMap;   
  9. import java.util.Iterator;   
  10. import java.util.Vector;   
  11.   
  12. public class FileConverter {   
  13.     public static final int BUFFER_SIZE = 1024;   
  14.   
  15.     public static final int EOF = -1;   
  16.   
  17.     public static final int EOL = -1;   
  18.   
  19.     public static final String BACK_SLASH = "\\";  
  20.  
  21.     public static final String REG_BACK_SLASH = "\\\\";  
  22.  
  23.     public static final String NEW_LINE_WINDOWS = "\r\n";  
  24.  
  25.     public static final String NEW_LINE_UNIX = "\n";  
  26.  
  27.     public static final String NEW_LINE_MACOS = "\r";  
  28.  
  29.     public static OutputStreamWriter writer = null;  
  30.  
  31.     public static final int SIMULATE_COUNT = 30;  
  32.  
  33.     public static final String DEFAULT_FROM_ENCODING = "EUC-KR";  
  34.  
  35.     public static final String DEFAULT_TO_ENCODING = "UTF-8";  
  36.  
  37.     public static final String DEFAULT_SOURCE_PATH = "C:\\TEMP";  
  38.  
  39.     private String from = "EUC-KR";  
  40.  
  41.     private String to = "UTF-8";  
  42.  
  43.     private String path = "C:\\TEMP";  
  44.       
  45.     private String topath="C:\\TEMP1";  
  46.  
  47.     public String getTopath() {  
  48.         return topath;  
  49.     }  
  50.  
  51.     public void setTopath(String topath) {  
  52.         this.topath = topath;  
  53.     }  
  54.  
  55.     public String getFrom() {  
  56.         return from;  
  57.     }  
  58.  
  59.     public void setFrom(String string) {  
  60.         from = string;  
  61.     }  
  62.  
  63.     public String getTo() {  
  64.         return to;  
  65.     }  
  66.  
  67.     public void setTo(String string) {  
  68.         to = string;  
  69.     }  
  70.  
  71.     public String getPath() {  
  72.         return path;  
  73.     }  
  74.  
  75.     public void setPath(String string) {  
  76.         path = string;  
  77.     }  
  78.  
  79.     public static void convertFile(String string, String string_0_,  
  80.             String string_1_, String string_2_) throws Exception { //实现单个文件的拷贝  
  81.         InputStreamReader inputstreamreader = new InputStreamReader(  
  82.                 new FileInputStream(string), string_0_);  
  83.         File file = new File(string_1_);  
  84.         if (!file.getParentFile().exists())  
  85.             file.getParentFile().mkdirs();  
  86.         if (!file.exists())  
  87.             file.createNewFile();  
  88.         OutputStreamWriter outputstreamwriter = new OutputStreamWriter(  
  89.                 new FileOutputStream(string_1_), string_2_);  
  90.         char[] cs = new char[1024];  
  91.         int i = -1;  
  92.         while ((i = inputstreamreader.read(cs)) != -1) {  
  93.             outputstreamwriter.write(cs, 0, i);  
  94.             outputstreamwriter.flush();  
  95.         }  
  96.         outputstreamwriter.close();  
  97.     }  
  98.  
  99.     public static void listFiles(File file,  
  100.             OutputStreamWriter outputstreamwriter) throws Exception {  
  101.         if (file.isDirectory() && file.listFiles() != null) {  
  102.             File[] files = file.listFiles();  
  103.             for (int i = 0; i < files.length; i++) {  
  104.                 File file_3_ = new File(files[i].getAbsolutePath());  
  105.                 if (file_3_.isDirectory())  
  106.                     listFiles(file_3_, outputstreamwriter);  
  107.                 else if (file_3_.isFile()) {  
  108.                     outputstreamwriter.write(new StringBuilder().append(  
  109.                             file_3_.getAbsolutePath()).append("\r\n")  
  110.                             .toString());  
  111.                     outputstreamwriter.flush();  
  112.                 } else  
  113.                     System.out.println("What's this?");  
  114.             }  
  115.         }  
  116.     }  
  117.  
  118.     public static Vector listSubFile(File file) throws Exception { //遍历源文件的目录及字文件夹,这种遍历本来可以写一个Composite Pattern来实现,时间比较紧,我就没做  
  119.         Vector vector = new Vector();  
  120.         if (file.isDirectory() && file.listFiles() != null) {  
  121.             File[] files = file.listFiles();  
  122.             for (int i = 0; i < files.length; i++) {  
  123.                 File file_4_ = new File(files[i].getAbsolutePath());  
  124.                 if (file_4_.isDirectory())  
  125.                     vector.addAll(listSubFile(file_4_));  
  126.                 else if (file_4_.isFile())  
  127.                     vector.add(file_4_.getAbsolutePath());  
  128.                 else  
  129.                     System.out.println("What's this?");  
  130.             }  
  131.         }  
  132.         return vector;  
  133.     }  
  134.  
  135.     public static HashMap restoreFiles(File file,File toFile, String string)  
  136.             throws Exception { //把源文件的目录作为key值,把目标目录+useri+以后文件目录或文件的名字做为value放到HashMap中  
  137.         HashMap hashmap = new HashMap();  
  138.         Vector vector = listSubFile(file);  
  139.         Iterator iterator = vector.iterator();  
  140.         while (iterator.hasNext()) {  
  141.             String string_5_ = (String) iterator.next();  
  142.             String string_6_ = doubleBackSlash(file.getAbsolutePath());  
  143.             String string_7_ = doubleBackSlash(toFile.getAbsolutePath());  
  144.             string_7_ = string_7_.concat("\\\\").concat(string);  
  145.             hashmap  
  146.                     .put(string_5_, string_5_  
  147.                             .replaceFirst(string_6_, string_7_));  
  148.         }  
  149.         return hashmap;  
  150.     }  
  151.  
  152.     public static void convertMultiFiles(File file, File toFile,String string,  
  153.             String string_8_, String string_9_) throws Exception { //执行拷贝了  
  154.         HashMap hashmap = restoreFiles(file,toFile,string);  
  155.         Iterator iterator = hashmap.keySet().iterator();  
  156.         while (iterator.hasNext()) {  
  157.             String string_10_ = (String) iterator.next();  
  158.             convertFile(string_10_, string_8_,  
  159.                     (String) hashmap.get(string_10_), string_9_);  
  160.         }  
  161.     }  
  162.  
  163.     public static void setWriter() throws Exception {  
  164.         writer = new OutputStreamWriter(new FileOutputStream(  
  165.                 "D:\\temp.tree.txt"), "GBK");  
  166.     }  
  167.  
  168.     public static void closeWriter() throws Exception {  
  169.         writer.close();  
  170.     }  
  171.  
  172.     public static String doubleBackSlash(String string) {  
  173.         StringBuffer stringbuffer = new StringBuffer(string);  
  174.         int i = -1;  
  175.         while ((i = stringbuffer.indexOf("\\", ++i)) != -1)  
  176.             stringbuffer.insert(++i, "\\");  
  177.         return stringbuffer.toString();  
  178.     }  
  179.  
  180.     public static boolean checkCRLF(String string, String string_11_) {  
  181.         boolean bool = false;  
  182.         if (string != null && string.length() >= string_11_.length()  
  183.                 && string.lastIndexOf(string_11_) != -1)  
  184.             bool = true;  
  185.         return bool;  
  186.     }  
  187.  
  188.     public static String trailingTrim(String string, String string_12_) {  
  189.         if (string != null && string.length() >= string_12_.length())  
  190.             string = string.substring(0, string.indexOf(string_12_));  
  191.         return string;  
  192.     }  
  193.  
  194.     public FileConverter() {  
  195.         path = "C:\\TEMP";  
  196.     }  
  197.  
  198.     public void inputPath() {//获取System.in的输入,去掉回车符,并把要copy的目录与目标目录用空格分开  
  199.         String s = "";  
  200.         InputStreamReader inputstreamreader = new InputStreamReader(System.in);  
  201.         BufferedReader bufferedreader = new BufferedReader(inputstreamreader);  
  202.         System.out.println("Unix: ctrl-d or ctrl-c to exit.\nWindows:Type ctrl-z or ctrl-c to exit.\nPlease " +  
  203. "input source path:"  
  204. );  
  205.         try  
  206.         {  
  207.             int i = bufferedreader.read();  
  208.             do  
  209.             {  
  210.                 s = (new StringBuilder()).append(s).append((char)i).toString();  
  211.                 if(i == 10 && checkCRLF(s, "\r\n"))  
  212.                 {  
  213.                     s = trailingTrim(s, "\r\n");  
  214.                     if(s.length() == 0)  
  215.                     {  
  216.                         System.out.print("The default path: C:\\temp will be used for source path.");  
  217.                     }  
  218.                     break;  
  219.                 }  
  220.                 i = bufferedreader.read();  
  221.             } while(true);  
  222.             System.out.println((new StringBuilder()).append("Read: ").append(s).toString());  
  223.             bufferedreader.close();  
  224.         }  
  225.         catch(IOException ioexception)  
  226.         {  
  227.             ioexception.printStackTrace();  
  228.         }  
  229.         String[] temp=s.split(" ");  
  230.         setPath(temp[0]);//set copy的目录  
  231.         this.setTopath(temp[1]);//set 目标目录  
  232.         File toFile=new File(topath);  
  233.         toFile.mkdir();//生成目标目录。  
  234.     }  
  235.  
  236.     public void start() throws Exception {  
  237.         inputPath();  
  238.         String[] strings = new String[350];  
  239.         for (int i = 0; i < strings.length; i++)  
  240.             strings[i] = new StringBuilder().append("user").append(i + 1)  
  241.                     .toString();  
  242.         File file = new File(path);  
  243.         File toFile=new File(topath);  
  244.         ThreadGroup threadgroup = new ThreadGroup("APP TEST");  
  245.         Thread[] threads = new Thread[350];  
  246.         for (int i = 0; i < threads.length; i++) {//生成350个SimulateThread对象并把在目标目录生成的文件夹的名称也作为参数  
  247.             threads[i] = new SimulateThread(threadgroup, file,toFile, strings[i]);  
  248.             threads[i].start();  
  249.         }  
  250.         for (;;) {  
  251.             int i = threadgroup.activeCount();  
  252.             if (i <= 0)  
  253.                 break;  
  254.             Thread.sleep(500L);  
  255.         }  
  256.         System.out.println("Done.");   
  257.     }   
  258.   
  259.     public static void main(String[] strings) throws Exception {   
  260.         new FileConverter().start();//创建一个FileConverter对象并且调用它的start方法   
  261.     }   
  262.   
  263. }   
好了,破于时间注释也不多写了,以上的代码大多都能看懂,俺也不多说了.
可以把他们的class文件打成jar文件,在 manifest.MF 写上Main-Class: FileConverter再写一个批处理run.bat
java -jar jar包名
噢了。。。。。。。。。。。。。。。。。。
对了还有一个问题就是文件的目录名及文件名不应该出现空格,因为以空格来截取拷贝的目录和目标目录的。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics