复制文件,并重命名

总体思路:1. 先复制文件到指定目录下;

       2. 根据需要,修改文件名称


 

(1)复制文件 实现代码:

例如:把“D:\照片”目录下的文件复制到“D:\姓名”目录下。

/**
* 描述:复制文件 到 目标路径
* @param srcPath
* @param targetPath
* @throws Exception
*/
public static void copyFile(String srcPath, String targetPath) throws Exception{
File srcFolder = new File(srcPath);
File tarFolder = new File(targetPath);
if(!tarFolder.exists()){
tarFolder.mkdirs();
}

File[] srcFiles = srcFolder.listFiles();
InputStream ins = null;
OutputStream ots = null;
for(File srcFile:srcFiles){
if(srcFile.exists()){
String fileName = srcFile.getName();
ins = new FileInputStream(srcFile);
ots = new FileOutputStream(targetPath+"\\"+fileName);
int reader = -1;
byte[] readByte = new byte[2048];
while((reader=ins.read(readByte))!=-1){
ots.write(readByte,0,reader);
}
}
}
if(ots!=null){
ots.close();
}
if(ins!=null){
ins.close();
}
}

(2)修改文件名称:renameTo(File targetFile)函数。

posted @ 2016-11-08 10:42  小妮儿玩博客  阅读(2197)  评论(0编辑  收藏  举报