java拷貝指定文件夾下的指定文件類型


例如:把C:\Windows\SysWOW64下的所有dll文件拷貝到C:\Users\Administrator\Desktop\64dll這個目錄

 1 package com.xiaostudy.copyFile;
 2 
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.FileOutputStream;
 6 import java.io.IOException;
 7 import java.util.Scanner;
 8 
 9 public class CopyFile {
10 
11     /**
12      * @param args
13      */
14     public static void main(String[] args) {
15         Scanner scanner = new Scanner(System.in);
16         System.out.print("請輸入復制的文件夾路徑:");
17         String inFiles = scanner.next();//String inFile = "C:\\Windows\\SysWOW64";
18         System.out.print("請輸入拷貝到的文件夾路徑:");
19         String outFiles = scanner.next();//String outFile = "C:\\Users\\Administrator\\Desktop\\64dll";
20         System.out.print("請輸入要復制文件類型,比如說txt文件,就輸入:txt\r\n請輸入:");
21         String type = scanner.next();
22         
23         FileInputStream fis = null;
24         FileOutputStream fos = null;
25         try {
26             File outFiled = new File(outFiles);
27             if (!outFiled.exists()) {
28                 outFiled.mkdirs();
29             }
30 
31             File files = new File(inFiles);
32 
33             if (files.exists()) {
34                 File[] listFiles = files.listFiles();
35                 if (listFiles != null && listFiles.length > 0) {
36                     for (File file : listFiles) {
37                         String fileName = file.getName();
38                         String[] str = fileName.split("\\.");
39                         if (str[str.length-1].equals(type)) {
40                             fis = new FileInputStream(file);
41                             fos = new FileOutputStream(new File(outFiled, fileName));
42                             byte[] buf = new byte[1024];
43                             int bytesRead;
44                             while ((bytesRead = fis.read(buf)) > 0) {
45                                 fos.write(buf, 0, bytesRead);
46 
47                             }
48                         }
49                     }
50                 }
51 
52             }
53         } catch (IOException e) {
54             e.printStackTrace();
55         } finally {//關閉資源
56             if(fos != null) {
57                 try {
58                     fos.close();
59                 } catch (IOException e) {
60                     e.printStackTrace();
61                 }
62             }
63             if(fis != null) {
64                 try {
65                     fis.close();
66                 } catch (IOException e) {
67                     e.printStackTrace();
68                 }
69             }
70         }
71     }
72 
73 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM