java学习

java学习

 

java 中文件的复制,查询,删除

javaIO中,文件的查询和删除,文件的复制程序如下:

普通的复制是:

public class Acopy {

 public void copy(String oldpath,String  newpath ) throws IOException {

    File of = new File(oldpath);

    File nf = new File(newpath);

    if(!nf.exists()){

      nf.createNewFile();

    }

    FileInputStream i = new FileInputStream(of); 

    FileOutputStream o = new FileOutputStream(nf);

    int b= 0;

    byte[] buffer = new byte[100];

    while((b=i.read(buffer))!=-1){

      o.write(buffer, 0, b-1);

    }

    i.close();

    o.flush();

    o.close();

  }

}

加强的复制是:

public class Bcopy {

 public void copy(String opath,String npath) throws IOException{

    File of = new File(opath);

    File nf = new File(npath);

    if(!nf.exists()){

      nf.createNewFile();

    }

    FileInputStream i = new FileInputStream(of);

    BufferedInputStream bi = new BufferedInputStream(i);

    FileOutputStream o = new FileOutputStream(nf);

    BufferedOutputStream bo = new BufferedOutputStream(o);

    int b = 0;

    byte[] buffer = new byte[100];

    while((b=bi.read(buffer))!=-1){

      bo.write(buffer, 0, b-1);

    }

    bi.close();

    bo.flush();

    bo.close();

  }

}

文件的查询是:

public void show(String path){

    File f = new File(path);

    if(f.isFile()){

      System.out.println(f.getPath());

    }else if(f.isDirectory()){

      File[] files = f.listFiles();

      if(files!=null){

        for(File file : files){

          if(file.isFile()){

            System.out.println(file.getPath());

          }else if(file.isDirectory()){

            System.out.println("["+file.getPath()+"]");

            show(file.getPath());

          }

        }

      }

    }

  }

文件的删除是:

public void del(String path){

    File f = new File(path);

    if(f.isFile()){

      f.delete();

    }else if(f.isDirectory()){

      File[] files = f.listFiles();

      if(files.length==0){

        f.delete();

      }else if(files!=null){

        for(File file : files){

          if(file.isFile()){

            file.delete();

          }else if(file.isDirectory()){

            del(file.getPath());

          }

        }

      }

    }

    f.delete();

  }

posted on 2011-11-26 12:27 杨军威 阅读(283) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜