资料的递归删除
文件的递归删除
package hashMap; import java.io.*; /** * 源文件复制的同名的目录下,创建源文件的副本 * @author 郑云飞 *data:2010年9月29日22:25 *步骤:1.将源文件重命名 * 2.将重命名后的文件复制的一个临时盘符中去 * 3.在将重命名的源文件重新回复原名称 * 4.将重新回复名称后的文件再次复制到目标路径中去 * 5.递归删除临时盘符中重命名后的文件 */ public class FileCopy { public static void main(String[] args) throws IOException { File sourceFile = new File("F:/123/456"); File targetFile = new File("F:/123/456"); if(sourceFile.getName().equals(targetFile.getName())) { System.out.println("文件已经存在,是否创建副本:"); System.out.println("*************1 是*************其他键 否*********"); char ok=(char)System.in.read(); if(ok=='1') { File copyfFile=new File(sourceFile.getAbsolutePath()+"附件");//定义一个文件的副本 sourceFile.renameTo(copyfFile);//步骤1 sourceFile=copyfFile;//步骤1 File ff=new File("C:/"+sourceFile.getParent().substring(3));//创建一个临时盘符 copy(sourceFile,ff);//步骤2 File temp=new File("C:/"+sourceFile.getParent().substring(3)+"/"+sourceFile.getName());//步骤 temp.renameTo(new File("C:/"+targetFile.getParent().substring(3)+"/"+targetFile.getName()));//步骤3 File f3=new File("C:/"+targetFile.getParent().substring(3)+"/"+targetFile.getName()); copy(f3,sourceFile.getParentFile());//步骤4 System.out.println(f3.getParent()+"******************************"); if(f3.getParent().length()==3) { del(f3); } else { del(f3.getParentFile());//步骤5 } } } else { copy(sourceFile, targetFile); } } /** * 文件的递归复制 * @param sourceFile * @param targetFile */ public static void copy(File sourceFile, File targetFile) { if(sourceFile.exists()) { if(!targetFile.exists()) { targetFile.mkdir(); } File tarpath = new File(targetFile, sourceFile.getName()); if (sourceFile.isDirectory())//如果源文件是一个目录 { tarpath.mkdir();//创建此目录到目标路径 System.out.println("目录"+tarpath.getName()+"赋值完成"); File[] dir = sourceFile.listFiles();//获取源文件下属的子文件 for(File f:dir) { copy(f,tarpath);//递归调用所有的子目录下面的文件 } } else//如果是文件,拷贝文件到相应的目录下面 { try { InputStream is = new FileInputStream(sourceFile); OutputStream os = new FileOutputStream(tarpath); byte[] buf = new byte[1024]; int len = 0; while ((len=is.read(buf))!=-1)//当缓冲区存放的有内容的时候 { os.write(buf,0,len);//将缓冲区的内存写入输出流os中 } System.out.println("文件"+tarpath.getName()+"复制完成"); if(is!=null) { is.close(); } if(os!=null) { os.close(); } } catch (Exception e) { e.printStackTrace(); } } } else { System.out.println("源文件不存在"); System.exit(0); } } /** * 文件的递归删除 * @param sourceFile * @throws IOException */ public static void del(File sourceFile) throws IOException { if(sourceFile.exists()) { if (sourceFile.isDirectory()) { sourceFile.deleteOnExit(); File[] dir = sourceFile.listFiles(); for(File f:dir) { del(f); } } else { sourceFile.deleteOnExit(); } } else { System.out.println("源文件不存在"); } } }