Java 將目錄下所有文件移至/復制到另一目錄


public void moveFiles(String oldPath, String newPath){
	String[] filePaths = new File(oldPath).list();

	if (filePaths && filePaths.size() > 0){
		if (!new File(newPath).exists()){
			new File(newPath).mkdirs();
		}
		
		for (int i=0; i<filePaths.size(); i++){
			if (new File(oldPath + File.separator + filePaths[i]).isDirectory()){
				moveFiles(oldPath + File.separator + filePaths[i], newPath + File.separator + filePaths[i]);
			}else if (new File(oldPath + File.separator + filePaths[i]).isFile()){
				//復制文件到另一個目錄
				copyFile(oldPath + file.separator + filePath[i], newPath + file.separator + filePath[i]);
				//移動文件至另一個目錄
				new File(oldPath + File.separator + filePaths[i]).renameTo(new File(newPath + File.separator + filePaths[i]));
			}
		}
	}
}

public void copyFile(String oldPath, String newPath) throws IOException {
	File oldFile = new File(oldPath);
	File file = new File(newPath);
	FileInputStream in = new FileInputStream(oldFile);
	FileOutputStream out = new FileOutputStream(file);;

	byte[] buffer=new byte[2097152];
        
	while((in.read(buffer)) != -1){
		out.write(buffer);
	}
}


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
  © 2014-2022 ITdaan.com 联系我们: