黑马程序员--把一个多层目录结构的文件夹复制到另一个地方

时间:2023-02-19 18:19:34

------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------

利用了递归的思想,在方法中调用本身的方法。

tip:先介绍几个方法,关于mkdir()和mkdirs()方法

mkdir()创建此抽象路径名称指定的目录(及只能创建一级的目录,且需要存在父目录)

mkdirs()创建此抽象路径指定的目录,包括所有必须但不存在的父目录。(及可以创建多级目录,无论是否存在父目录

renameto方法也可以把一个目录下的文件移动到另一个目录

public static void main(String[] args) throws IOException {

                  File fold = new File("D:\\A\\1.txt");//某路径下的文件
  String strNewPath = "D:\\A\\2.txt\\2.txt";//新路径
  File fnewpath = new File(strNewPath);
  if(!fnewpath.exists())
    fnewpath.mkdirs();
  File fnew = new File(strNewPath+fold.getName());
  fold.renameTo(fnew);

}

程序运行之后,将会把1.txt文本文件移动到D:\\A\\2.txt目录下,并重新命名为2.txt1.txt

renameto()方法demo

//以前是正文把一个多层目录结构的文件夹复制到另一个地方

/**
 * 复制文件夹或文件
 */
public class CopyDirectory {
// 源文件夹
static String url1 = "F:/a";
// 目标文件夹
static String url2 = "D:/aa";
public static void main(String args[]) throws IOException {
// 创建目标文件夹
if(!(new File(url2).exists())){
(new File(url2)).mkdirs();
}
// 获取源文件夹当前下的文件或目录
File[] file = (new File(url1)).listFiles();
for (int i = 0; i < file.length; i++) {
if (file[i].isFile()) {
// 复制文件

File f= new File(url2 + File.separator+ file[i].getName());
if(f.exists()){
System.out.println("存在文件");
}
System.out.println(f.getAbsolutePath());
copyFile(file[i], new File(url2 + File.separator + file[i].getName()));
}
if (file[i].isDirectory()) {
// 复制目录
String sourceDir = url1 + File.separator + file[i].getName();
System.out.println(sourceDir);
String targetDir = url2 + File.separator + file[i].getName();
System.out.println(targetDir);
copyDirectiory(sourceDir, targetDir);
}
}
System.out.println("end");
}


// 复制文件
public static void copyFile(File sourceFile, File targetFile)
throws IOException {
// 新建文件输入流并对它进行缓冲
FileInputStream input = new FileInputStream(sourceFile);
BufferedInputStream inBuff = new BufferedInputStream(input);
// 新建文件输出流并对它进行缓冲
FileOutputStream output = new FileOutputStream(targetFile);
BufferedOutputStream outBuff = new BufferedOutputStream(output);


// 缓冲数组
byte[] b = new byte[1024];
int len;
while ((len = inBuff.read(b)) != -1) {
outBuff.write(b, 0, len);
}
// 刷新此缓冲的输出流
outBuff.flush();


// 关闭流
inBuff.close();
outBuff.close();
output.close();
input.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);
}
}
}
}