復制文件,並重命名


總體思路: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)函數。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM