Java 将目录下所有文件移至/复制到另一目录

时间:2021-03-15 14:29:47
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);
	}
}