---------------------- 黑马程序员 Android培训、期待与您交流! ----------------------
因为见得多的面试题就是从一个盘复制文件到另一个盘,所以小试一下是否能够成功
注:C盘不成功,因为win8系统下复制C盘文件需要管理员权限,暂时不知道在JavaIO流中如何设置
/*
思路
1、通过盘符或者盘符下的所以文件和目录。
2、对盘符下的文件进行遍历,遍历的过程中定义盘条件。
3、如果是文件,直接复制,如果是目录,那就对目录进行迭代。
4、如果目录中的文件还是目录,那就对目录进行递归操作。
5、关闭所有流资源。
*/
package test20140925;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Test {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
copyRoot(new File("E:\\"),new File("D:\\test"));
}
/*
*
* 复制文件方法
*/
public static void copyFile(File dest, File src) throws IOException {
//新建一个FileInputStream对象
InputStream ips = new FileInputStream(src);
//新建一个FileOutputStream对象
OutputStream ops = new FileOutputStream(dest);
//字节
byte[] buf = new byte[1024];
//长度
int len = 0;
while ((len = ips.read(buf)) != -1) {
//写入
ops.write(buf, 0, len);
}
//关闭输入输出流
ips.close();
ops.close();
}
/*
*
* 复制目录下的文件。
*/
public static void copyDir(File dest, File src) throws IOException {
//可以在不存在的目录中创建文件夹。诸如:a\\b,既可以创建多级目录。
dest.mkdirs();
File[] dirAndFile = src.listFiles();
for (File dirOrFile : dirAndFile) {
if (dirOrFile.isFile()) {
copyFile(
new File(dest.getAbsolutePath() + "\\"+ dirOrFile.getName()),
new File(dirOrFile.getAbsolutePath()));
}else if (dirOrFile.isDirectory()) {
copyDir(
new File(dest.getAbsolutePath() + "\\"+ dirOrFile.getName()),
new File(dirOrFile.getAbsolutePath()));}
}
}
/*
*
* 复制整个盘符
*/
public static void copyRoot(File dest, File src) throws IOException {
File[] dirAndFile = src.listFiles();
if (src.exists()) {
for (File dirOrFile : dirAndFile) {
if (!dirOrFile.isHidden()) {
if (dirOrFile.isFile()) {
File destFile = new File(dest.getAbsolutePath() + "\\"+ dirOrFile.getName());
File srcFile = new File(src.getAbsolutePath() + "\\"+ dirOrFile.getName());
copyFile(destFile, srcFile);
}else if (dirOrFile.isDirectory()) {
File destDir =new File(dest.getAbsolutePath() + "\\"+ dirOrFile.getName());
File srcDir =new File(src.getAbsolutePath() + "\\"+ dirOrFile.getName());
copyDir(destDir, srcDir);}
}
}
}
}
}
---------------------- 黑马程序员 Android培训、期待与您交流! ----------------------