package fileutil;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileHelper
{
public static void main(String args[]) throws IOException
{
String url1 = "C:/Users/Administrator/Desktop/fishjoy/fishjoy"; // 源文件夹
String url2 = "E:/360/"; // 目标文件夹
(new File(url2)).mkdirs(); // 创建目标文件夹
File[] file = (new File(url1)).listFiles(); // 获取源文件夹当前下的文件或目录
for (int i = 0; i < file.length; i++)
{
if (file[i].isFile()) // 复制文件
{
String type = file[i].getName().substring(file[i].getName().lastIndexOf(".") + 1);
copyFile(file[i], new File(url2 + file[i].getName()));
}
if (file[i].isDirectory()) // 复制目录
{
String sourceDir = url1 + File.separator + file[i].getName();
String targetDir = url2 + File.separator + file[i].getName();
copyDirectiory(sourceDir, targetDir);
}
}
}
// 复制文件
public static void copyFile(File sourceFile, File targetFile) throws IOException
{
BufferedInputStream inBuff = null;
BufferedOutputStream outBuff = null;
try
{
inBuff = new BufferedInputStream(new FileInputStream(sourceFile));
outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));
byte[] b = new byte[1024 * 5];
int len;
while ((len = inBuff.read(b)) != -1)
{
outBuff.write(b, 0, len);
}
outBuff.flush();
}
finally
{
if (inBuff != null)
inBuff.close();
if (outBuff != null)
outBuff.close();
}
}
// 复制文件夹
public static void copyDirectiory(String sourceDir, String targetDir)
throws IOException
{
(new File(targetDir)).mkdirs();
File[] file = (new File(sourceDir)).listFiles();
for (int i = 0; i < file.length; i++)
{
if (file[i].isFile())
{
File sourceFile = file[i];
File targetFile = new File(new File(targetDir).getAbsolutePath() + File.separator + file[i].getName());
copyFile(sourceFile, targetFile);//递归调用
}
if (file[i].isDirectory())
{
String dir1 = sourceDir + "/" + file[i].getName();
String dir2 = targetDir + "/" + file[i].getName();
copyDirectiory(dir1, dir2);
}
}
}}