Java IO实现文件以及文件夹的复制

public class FolderCopy {
	public static void copyFolder(File[] s,File d){
		if(!d.exists()){
			d.mkdir();
		}
		for (int i = 0; i < s.length; i++) {
			if(s[i].isFile()){
				try {
					FileInputStream fis = new FileInputStream(s[i]);
					FileOutputStream fos = new FileOutputStream(new File(d.getPath()+File.separator+s[i].getName()));
					byte [] data = new byte[fis.available()];
					if((fis.read(data)!=-1)){
						fos.write(data);
					}
					fos.flush();
					fos.close();
					fis.close();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(s[i].isDirectory()){
				File des = new File(d.getPath()+File.separator+s[i].getName());
				des.mkdir();
				copyFolder(s[i].listFiles(), des);
			}
		}
	}
	public static void main(String[] args) {
		File sourFile = null,desFile=null;
		String sourFoler ="src/com/hs";
		String desFoler = "desFoler";
		sourFile = new File(sourFoler);
		if(!sourFile.isDirectory()||!sourFile.exists()){
			System.out.println("源文件不存在");
                            return;
		}
		desFile = new File(desFoler);
		desFile.mkdir();
		copyFolder(sourFile.listFiles(), desFile);
	}

}

你可能感兴趣的:(java)