Chinaunix首页 | 论坛 | 博客
  • 博客访问: 402750
  • 博文数量: 114
  • 博客积分: 7010
  • 博客等级: 少将
  • 技术积分: 1395
  • 用 户 组: 普通用户
  • 注册时间: 2008-07-05 17:54
文章分类

全部博文(114)

文章存档

2011年(2)

2009年(1)

2008年(111)

我的朋友

分类: Java

2008-08-02 20:46:59

递归?简单点:程序自己调用自己
实现文件的删除和拷贝,代码如下:

package com.viita;

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) 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+"/"+file2.getName());
            }
            
        }else
        {
            copy(path1,path2);
        }
    }
    
    //拷贝单个文件的方法

    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");
//        dp.copyFiles("c:/新建文件夹", "c:/xiao");

    }

}

阅读(2683) | 评论(0) | 转发(0) |
0

上一篇:海盗分金币问题

下一篇:Java 递归

给主人留下些什么吧!~~