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 }