1 package com.common.file;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.FileNotFoundException;
6 import java.io.FileOutputStream;
7 import java.io.IOException;
8 import java.io.InputStream;
9 import java.io.OutputStream;
10 import java.text.DateFormat;
11 import java.util.Date;
12 import java.util.Iterator;
13
14 import javax.swing.text.html.HTMLDocument.HTMLReader.FormAction;
15
16 /**
17 *
18 * 功能描述:
19 *
20 * @author Administrator
21 * @Date Jul 19, 2008
22 * @Time 9:46:11 AM
23 * @version 1.0
24 */
25 public class FileUtil {
26
27 /**
28 * 功能描述:列出某文件夹及其子文件夹下面的文件,并可根据扩展名过滤
29 *
30 * @param path
31 * 文件夹
32 */
33 public static void list(File path) {
34 if (!path.exists()) {
35 System.out.println("文件名称不存在!");
36 } else {
37 if (path.isFile()) {
38 if (path.getName().toLowerCase().endsWith(".pdf")
39 || path.getName().toLowerCase().endsWith(".doc")
40 || path.getName().toLowerCase().endsWith(".chm")
41 || path.getName().toLowerCase().endsWith(".html")
42 || path.getName().toLowerCase().endsWith(".htm")) {// 文件格式
43 System.out.println(path);
44 System.out.println(path.getName());
45 }
46 } else {
47 File[] files = path.listFiles();
48 for (int i = 0; i < files.length; i++) {
49 list(files[i]);
50 }
51 }
52 }
53 }
54
55 /**
56 * 功能描述:拷贝一个目录或者文件到指定路径下,即把源文件拷贝到目标文件路径下
57 *
58 * @param source
59 * 源文件
60 * @param target
61 * 目标文件路径
62 * @return void
63 */
64 public static void copy(File source, File target) {
65 File tarpath = new File(target, source.getName());
66 if (source.isDirectory()) {
67 tarpath.mkdir();
68 File[] dir = source.listFiles();
69 for (int i = 0; i < dir.length; i++) {
70 copy(dir[i], tarpath);
71 }
72 } else {
73 try {
74 InputStream is = new FileInputStream(source); // 用于读取文件的原始字节流
75 OutputStream os = new FileOutputStream(tarpath); // 用于写入文件的原始字节的流
76 byte[] buf = new byte[1024];// 存储读取数据的缓冲区大小
77 int len = 0;
78 while ((len = is.read(buf)) != -1) {
79 os.write(buf, 0, len);
80 }
81 is.close();
82 os.close();
83 } catch (FileNotFoundException e) {
84 e.printStackTrace();
85 } catch (IOException e) {
86 e.printStackTrace();
87 }
88 }
89 }
90
91 /**
92 * @param args
93 */