此用来记录平时练习.
class FileCopy extends Thread
{
private String strOldpath;
private String strNewPath;
public FileCopy(String strOldpath,String strNewPath)
{
this.strOldpath = strOldpath;
this.strNewPath = strNewPath;
}
@Override
public void run()
{
copyFile(strOldpath, strNewPath);
}
//2.拷贝文件
public static void copyFile(String strOldpath,String strNewPath)
{
try
{
File fOldFile = new File(strOldpath);
if (fOldFile.exists())
{
int byteread = 0;
InputStream inputStream = new FileInputStream(fOldFile);
FileOutputStream fileOutputStream = new FileOutputStream(strNewPath);
byte[] buffer = new byte[1024*1024];
while ( (byteread = inputStream.read(buffer)) != -1)
{
fileOutputStream.write(buffer, 0, byteread);
}
inputStream.close();
fileOutputStream.close();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
//throw new CustomException(ErrorCodeConstant.FILE_NOT_EXISTS , e);
}
catch (IOException e)
{
e.printStackTrace();
//throw new CustomException(ErrorCodeConstant.FILE_IO_ERROR);
}
}
}
public class Demo7
{
// 线程service 20个
private ExecutorService executorService = null;
public Demo7 ()
{
executorService = Executors.newFixedThreadPool(20);
}
/**
* 1.拷贝文件夹
* @param source
* @param target
*/
public void copyFolder(String source,String target)
{
//旧文件夹
File fOldFolder = new File(source);
try
{
//新文件夹
File fNewFolder = new File(target);
//不存在就创建一个文件夹
if (!fNewFolder.exists())
{
fNewFolder.mkdirs();
}
//获取旧文件夹里面所有的文件
File [] arrFiles = fOldFolder.listFiles();
Thread fileCopy = null;
for (int i = 0; i < arrFiles.length; i++)
{
System.out.println("处理:" + arrFiles[i].getPath() );
//从原来的路径拷贝到现在的路径,拷贝一个文件
if (arrFiles[i].isDirectory())
{
copyFolder(arrFiles[i].getPath(), target + File.separator + arrFiles[i].getName());
}
else
{
fileCopy = new FileCopy(source+"/"+arrFiles[i].getName(), target+"/"+arrFiles[i].getName());
executorService.submit(fileCopy);
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
Demo7 demo7 = new Demo7();
demo7.copyFolder("源文件地址","目标文件地址");
System.out.println("拷贝完成");
}
}