package com.smalt.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JTextArea;
/**
* java遍历文件夹并复制文件到指定目录
*/
public class TestRead {
// 允许复制的文件类型
public static String[] filterFile = { ".java", ".xml", ".xdl",
".properties", ".sql", ".jupiter", ".wsdl", ".txt" };
private long total = 0l;
// private static Pattern pattern =
// Pattern.compile("[A-z][:]/[A-z]*/OMC[0-9A-z]{0,}");
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.println("输入源地址:");
String srcStr = scanner.next();
String destStr;
System.out.println("输入目标地址:");
destStr = scanner.next();
String answer = null;
do {
File src = new File(srcStr);
File des = new File(destStr);
new TestRead().copyFolder(src, des, new String[] { ".java", ".xml",
".xdl", ".properties", ".sql", ".jupiter", ".txt" }, null);
System.out.println("Continue ?y or n");
answer = scanner.next();
} while (answer.equalsIgnoreCase("Y"));
scanner.close();
}
/**
* 复制文件夹
*
* @param folder
* @param filterFile
* @param status
* @throws Exception
*/
public void copyFolder(File srcFolder, File destFolder,
String[] filterFile, JTextArea status) throws Exception {
File[] files = srcFolder.listFiles();
for (File file : files) {
if (file.isFile()) {
String pathname = destFolder + File.separator + file.getName();
for (String suff : filterFile) {
if (pathname.endsWith(suff)) {
File dest = new File(pathname);
File destPar = dest.getParentFile();
destPar.mkdirs();
if (!dest.exists()) {
dest.createNewFile();
}
copyFile(file, dest, status);
}
}
} else {
copyFolder(file, destFolder, filterFile, status);
}
}
}
/***
* 复制文件
*
* @param src
* @param dest
* @param status
* @throws IOException
*/
private void copyFile(File src, File dest, JTextArea status)
throws Exception {
BufferedInputStream reader = null;
BufferedOutputStream writer = null;
try {
reader = new BufferedInputStream(new FileInputStream(src));
writer = new BufferedOutputStream(new FileOutputStream(dest));
byte[] buff = new byte[reader.available()];
while ((reader.read(buff)) != -1) {
writer.write(buff);
}
total++;
String temp = "\ncopy:\n" + src + "\tsize:" + src.length()
+ "\nto:\n" + dest + "\tsize:" + dest.length()
+ "\n complate\n totoal:" + total;
System.out.println(temp);
// status.append(temp);
} catch (Exception e) {
throw e;
} finally {
writer.flush();
writer.close();
reader.close();
}
}
}
没有评论:
发表评论