文件的删除和拷贝,又加了些方法拷贝整个文件下各种后缀的文件

来源:互联网 发布:白夜追凶国外知乎 编辑:程序博客网 时间:2024/06/05 10:19

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

public class Dptest {

 // 删除制定文件夹的所有文件及根文件夹

 public void deleteFile(String path) {

  // TODO Auto-generated method stub

  File f = new File(path);

  if (f.isDirectory())

  {

   File[] file = f.listFiles();

   for (File file2 : file) {

    this.deleteFile(file2.toString());

    file2.delete();

   }

  } else

  {

   f.delete();

  }

  f.delete();

 }

 // 拷贝整个文件夹的方法

 public void copyFiles(String path1, String path2,String geshi) throws Exception {

  // TODO Auto-generated method stub

  File file = new File(path1);

  if (file.isDirectory())

  {

   File f = new File(path2);

   if (!f.exists())
    f.mkdir();

   File[] files = file.listFiles();

   for (File file2 : files) {

    // System.out.println(file2.toString()+"-----"+path2+"/"+file2.getName());
               copyFiles(file2.toString(), path2 ,geshi);

   }

  } else

  {
   String geshis[]=geshi.split("#");
     for (int i = 0; i < geshis.length; i++) {
     if(file.getName().endsWith(geshis[i]))
                {
              String filePath=getFileName(path2,file.getName(),0);
              System.out.println(path1+":"+filePath);
        copy(path1, filePath);
                }
   }
   
              

  }

 }
 
 private String getFileName(String filePath,String filename,int num)
 {  
  
   File files=new File(filePath+filename);
   while(files.exists())
   {
    num=num+1;
    files=new File(filePath+num+filename);
   
   }
 
        return filePath+files.getName();
     
 
 }

 // 拷贝单个文件的方法

 public void copy(String path1, String path2) throws IOException {

  // TODO Auto-generated method stub

  DataInputStream in = new DataInputStream(

  new BufferedInputStream(

  new FileInputStream(path1)));

  byte[] date = new byte[in.available()];

  in.read(date);

  DataOutputStream out = new DataOutputStream(

  new BufferedOutputStream(

  new FileOutputStream(path2)));

  out.write(date);

  in.close();

  out.close();

 }

 public static void main(String[] args) throws Exception {

  Dptest dp = new Dptest();

  //dp.deleteFile("c:/wmpub");
     //1 拷贝源路径,2:拷贝后路径, 3:格式,格式以#号隔开
//  dp.copyFiles("D:/jsss", "D:/jsssss/",".js#.php");

  
  String[] aa = "aaa#bbb#ccc".split("#");
  
  for(int i=0;i<aa.length;i++) {
   System.out.println(aa[i]);
  }
 }

}

原创粉丝点击