黑马程序员技术交流社区
标题:
来道面试题尝尝鲜
[打印本页]
作者:
micro_hx
时间:
2015-6-21 23:55
标题:
来道面试题尝尝鲜
试题:
从一个盘符拷贝文件夹到另一个盘符,文件夹里需要有嵌套文件夹。(其中内部存在很多大文件,注意复制效率)
题目可以有很多思路,本屌丝面试写的一种方法,现在奉上:
package com.itheima;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
/**
* 完全复制某个文件夹下所有内容
* 将D:\\test复制到 E:\\test中
* @author Administrator
*/
public class Test3 {
//String为文件路劲,Boolean为文件夹还是文件
static Map<String,Boolean> container = new HashMap<String,Boolean>();
public static void main(String[] args) {
listFile("D:\\test");
copyFile();
}
/**
* 罗列文件名称
* @param filePath
*/
static void listFile(String filePath){
File parentFile = new File(filePath);
File[] files = parentFile.listFiles() ;
if(files != null && files.length > 0){
for(File file : files){
String fileName =file.getAbsolutePath() ;
if(file.isDirectory()){
container.put(fileName, true);
listFile(fileName);
}else{
container.put(fileName, false);
}
System.out.println(file.getAbsolutePath());
}
}
}
static void copyFile(){
Iterator<Entry<String,Boolean>> iterator = container.entrySet().iterator() ;
BufferedInputStream input = null ;
BufferedOutputStream output = null ;
while(iterator.hasNext()){
Entry<String,Boolean> entry = iterator.next();
String filePath = entry.getKey() ;
boolean isDir = entry.getValue() ;
if(filePath != null){
String copyPath = "E:"+filePath.substring(2);
if(isDir){
File newDir = new File(copyPath);
if(!newDir.exists())
newDir.mkdirs() ;
}else{
String dirPath = copyPath.substring(0, copyPath.lastIndexOf("\\")+1 ) ;
File newDir = new File(dirPath);
if(!newDir.exists())
newDir.mkdirs();
File newFile = new File(copyPath);
if(!newFile.exists()){
try {
newFile.createNewFile();
//写入文件
input = new BufferedInputStream(new FileInputStream(new File(filePath)));
output = new BufferedOutputStream(new FileOutputStream(newFile));
byte[] buf = new byte[1024*50];
int len = 0 ;
while((len = input.read(buf)) != -1){
output.write(buf, 0, len);
output.flush();
}
} catch (IOException e) {
e.printStackTrace();
}finally{
if(input != null){
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(output != null){
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
}
}
}
复制代码
看看大家思路啊。。。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2