Java实现任意文件及文件夹拷贝功能:(图片、MP3、电影等)
/*
* 需求:1.将C盘指定的一个文件夹(包含文件夹内的所有文件夹和所有文件,多层嵌套)复制到D盘中。
* 思路:
* 1.给出C:oldPath和D:newPath的路径
* 2.如果文件夹不存在 则建立新文件夹,根据路径创建文件对象
* 3.用list()数组列出原给定目录内容,在for中用endsWith判断结尾‘/’来创建临时路径变量
* 4.判断:如果临时路径变量是文件,则创建文件输入和输出字节流进行拷贝(读取和写入) * 5.如果是文件目录,则新旧路径添加\,进行递归 * */
import java.io.File;
import java.io.FileInputStream; import java.io.FileOutputStream;
public class CopyFolderDemo01 {
public static void main(String[] args) {
String oldPath = \
String newPath = \ copyFolder(oldPath,newPath); }
public static void copyFolder(String oldPath, String newPath) {
try { File createFile =new File(newPath); createFile.mkdirs(); // 如果文件夹不存在 则建立新文件夹
File a = new File(oldPath);
String[] file = a.list();//列出给定目录中的内容 File temp = null;
for (int i = 0; i < file.length; i++) {
if (oldPath.endsWith(File.separator)) { temp = new File(oldPath + file[i]);
} else { temp = new File(oldPath + File.separator + file[i]); }
if (temp.isFile()) {//如果是文件 FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(newPath + \byte[] b = new byte[1024]; int len;
while ((len = input.read(b)) != -1) {
}
output.write(b, 0, len); output.flush(); output.close(); input.close();
} }
}
if (temp.isDirectory()) {// 如果是目录,即子文件夹 copyFolder(oldPath + \重新遍历 }
} catch (Exception e) {
System.out.println(\复制文件夹内容操作出错\e.printStackTrace(); } }