您的位置:首页 > 编程语言 > Java开发

java复制文件、文件夹

2012-06-11 15:09 281 查看
//复制文件到新的路径下

public static void copyFile(String oldPath,String newPath){

File file=new File(oldPath);

InputStream is=null;

OutputStream os=null;

int byteReade=0;

File newPathFile=new File(newPath);

if((!newPathFile.exists()) && file.exists()){

try {

if(!newPathFile.getParentFile().exists()){//目标文件夹不存在

newPathFile.getParentFile().mkdirs();

}

is=new FileInputStream(file);

os=new FileOutputStream(newPath);

byte[] buffer=new byte[1024];

try {

while((byteReade=is.read(buffer))!=-1){

os.write(buffer, 0, byteReade);

}

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally{

try {

is.close();

os.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}



}

}

}



//复制整个文件夹

public static void copyFold(String oldPath,String newPath){

File oldFold=new File(oldPath);

File newFold=new File(newPath);

File[] files=null;

if(!oldFold.exists()){

return;

}else{

files=oldFold.listFiles();

for(int i=0;i<files.length;i++){

if(files[i].isFile()){

copyFile(files[i].getAbsolutePath(),newPath+"/"+files[i].getName());

}else if(files[i].isDirectory()){

copyFold(files[i].getAbsolutePath(),newPath+"/"+files[i].getName());

}

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: