public static void main(String[] args) throws Exception {
//复制到哪个路径(path)中
String path = "E:\\main";
File file = new File("F:\\main");
copyAll(file, path);
}
public static void copy(File file, String path) throws Exception {
FileInputStream in = new FileInputStream(file);
FileOutputStream out = new FileOutputStream(path + file.getName());
byte[] by = new byte[1024];
int len = 0;
while ((len = in.read(by)) != -1) {
out.write(by, 0, len);
}
}
public static void copyAll(File file, String path) throws Exception {
File outFile = new File(path);
//创建文件夹,如果文件夹已存在则创建失败返回false
outFile.mkdirs();
File[] files = file.listFiles();
for (File file1 : files) {
//如果是文件就复制文件
if (file1.isFile()) {
copy(file1, path + File.separator);
} else {
//如果是文件夹,就创建文件夹,并复制文件,这就是copyAll()的功能,所以用递归
copyAll(file1, outFile.getPath() + File.separator + file1.getName());
}
}
}
File.separator代表系统默认文件目录分隔符,即我们所说的“斜线”
但由于在Windows系统中分隔符为“ \ ”
而在Linux系统中分隔符为“ / ”
//在temp目录下建立一个test.txt文件
File file1 = new File ("C:\temp\test.txt");//Windows
File file2 = new File ("/temp/test.txt");//linux和UNIX
因此File.separator的作用就是保证在任何系统都可以正确表示斜线
此外 File 类还有:
1、separatorChar
代表系统的默认名称分隔符,它被表示为一个字符串(只包含一个字符)。
2、pathSeparator
此字符用于分隔以路径列表形式给定的文件序列中的文件名
在 UNIX和Linux系统上此字段为 ’ : ’
在Windows 系统上为 ’ ; ’
3、pathSeparatorChar
代表系统的路径分隔符,它被表示为一个字符串(只包含一个字符)