import java.io.*;
import java.util.*;
class rr {
public static void main(String[] args) throws IOException{
File file = new File("D:\\JDK6.0\\java201206");
List<String> data = new ArrayList<String>();
data=showDir(file,data);
fileCopy("E:\\copy",data);
}
public static List<String> showDir(File f,List<String> data)throws IOException{
File[] fi =f.listFiles();
for(int i=0;i<fi.length;i++){
if(fi[i].isDirectory())
showDir(fi[i],data);
else{
if(fi[i].getAbsolutePath().endsWith(".java"))
data.add(fi[i].getAbsolutePath());//这里用路径,用Name就可源文件搭不上关系了
}
}
return data;
}
public static void fileCopy(String index,List<String> list)throws IOException {
File fileNext=new File(index);
if(!fileNext.exists())
fileNext.mkdir();
BufferedReader br=null;
BufferedWriter bw=null;
for(String fi:list){
File file=new File(fi);
if(file.isDirectory())
break;
bw=new BufferedWriter(new FileWriter(fileNext+"\\\\"+file.getName()));
br=new BufferedReader(new FileReader(fi));;
String s=null;
while((s=br.readLine())!=null){
bw.write(s);
bw.newLine();
bw.flush();
}
}
bw.close();
br.close();
}
}
-------------------------------------------------------------------------------------------------------------------------------------
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class CopyFolder
{
public static void main(String[] args)
{
//只要不是错误目录就行,文件夹结尾加不加
//斜杠都行,没有区别
Copy("C:/Program Files/office2007", "D:/");
}
public static void Copy(String srcPath, String desPath)
{
File srcFile = new File(srcPath);
File desFile = new File(desPath);
if(srcFile.isDirectory())
{
//如果是文件夹的话,路径需要增加一个斜杠,
//用File.getpath可以避免输入的路径有斜杠
//和没有斜杠导致的一些问题
srcPath = srcFile.getPath()+File.separator;
desPath = desFile.getPath()+File.separator;
System.out.println(srcPath + " -> " + desPath);
//遍历整个文件夹下的所有文件和子文件,
//并通过递归调用自己实现所有文件的复制
String[] fileList = srcFile.list();
for (String fileName : fileList)
{
Copy(srcPath+fileName, desPath+fileName);
}
}
//如果给定的源路径是文件
else if(srcFile.isFile())
{
System.out.println(srcPath + " -> " + desPath);
CopyFile(srcPath, desPath);
}
//如果源路径不合法
else
{
throw new IllegalArgumentException("源文件(夹)不存在");
}
}
public static void CopyFile(String srcPath, String desPath)
{
try
{
File srcFile = new File(srcPath);
File desFile = new File(desPath);
//仅当源文件为文件时才复制,目录无法创建流
//会抛出异常
if(srcFile.isFile())
{
desFile.getParentFile().mkdirs();
if(!desFile.exists()) //如果不存在就创建一个新文件
desFile.createNewFile();
//创建文件以及该路径里不存在的目录
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(desFile);
byte[] buffer = new byte[1024]; //定义一个 byte数组用于缓冲
int len;
while ((len = fis.read(buffer)) != -1) //循环判断不是文件的最后就写入
fos.write(buffer, 0, len);
} finally { //关闭流
fis.close();
fos.close();
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
|