文件或文件夹复制到另一个文件夹
public class FileCopy {
public static void main(String[] args) {
File sourceFile = new File("e:\\javaIO");
File targetFile = new File("e:\\javaFile");// 目标文件
System.out.println("共复制以下文件!");
copyDirectory(sourceFile, targetFile);
}
private static void copyDirectory(File sourceFile, File targetFile) {
if (sourceFile.isFile()) {// 如果是文件,则直接复制
copyFile(sourceFile, new File(targetFile, sourceFile.getName()));
System.out.println(sourceFile.getName()+"拷贝完成");
} else {//如果是目录,则遍历
File file = new File(targetFile, sourceFile.getName());//创建子文件夹
file.mkdirs();
System.out.println(file.getName()+"目录创建完成!");
File[] files = sourceFile.listFiles();
for (File file2 : files) {
copyDirectory(file2, file);
}
}
}
=================copyFile方法========================
- 方法一:用RandomAccessFile
private static void copyFile(File sourceFile, File targetDir) {
// TODO Auto-generated method stub
RandomAccessFile rafSource = null;
RandomAccessFile rafTarget =null;
try {
rafSource = new RandomAccessFile(sourceFile, "r");
rafTarget = new RandomAccessFile(targetDir, "rw");
rafTarget.setLength(sourceFile.length());
byte[] buff = new byte[1024*4];
int length = 0;
while((length=rafSource.read(buff)) != -1){
rafTarget.write(buff, 0, length);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
IOUtils.closeRandomAccessFile(rafTarget);
IOUtils.closeRandomAccessFile(rafSource);
}
}
- 方法二 IO流
public static void copyFile(File sourceFile, File targetFile) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(sourceFile));
bos = new BufferedOutputStream(new FileOutputStream(targetFile));
byte[] buff = new byte[1024];
int length;
while (-1 != (length = bis.read(buff))) {
bos.write(buff, 0, length);
}
bos.flush();
} catch (FileNotFoundException e) {
System.out.println("路径不存在");
System.exit(-1);
} catch (IOException e) {
System.out.println("文件读写错误");
System.exit(-1);
} finally {
IOUtils.closeInputStream(bis);
IOUtils.closeOutputStream(bos);
}
}
}
IOUtils工具类…..
border="0" width="330" height="86" src="//music.163.com/outchain/player?type=2&id=36190361&auto=1&height=66">