如何拷贝指定类型的文件以及如何更改拷贝的文件的扩展名

http://blog.csdn.net/caidie_huang/article/details/52738367

1.如何拷贝指定目录下的指定类型的文件到指定另一目录中:
使用过滤器(FilenameFilter)过滤文件

//案例1:文件拷贝案例-拷贝指定目录的指定类型文件到指定目录.  
    private static void test1() throws IOException {  
        //源文件  
        File srcDir = new File("file");  
        //目标文件  
        File desDir = new File("text");  

        //过滤.java文件,找到源目录中的java文件  
        File[] fs= srcDir.listFiles(new FilenameFilter(){  

            public boolean accept(File dir, String name) {  

                return new File(dir,name).isFile() && name.endsWith(".java");  
            }  

        });  

        //迭代出每一个文件对象,并拷贝  
        for (File file : fs) {  
            //创建流对象  
            InputStream in = new FileInputStream(file);  
            OutputStream out = new FileOutputStream(new File(desDir,file.getName()));  

            //IO操作  
            byte[] buffer = new byte[1024];  
            int len = -1;  
            while((len = in.read(buffer)) != -1){  
                out.write(buffer);  
            }  

            in.close();  
            out.close();  

        }  

    }  

2.如何更改拷贝的文件的扩展名:
在文件拷贝到目标文件的同时,将拷贝过来的文件的扩展名替换掉(使用到String类中的replaceAll方法

//分析:  比如把指定目录中所有的java文件拷贝到另一个目录中,把拷贝的所有文件的拓展名改为.txt.  
private static void test2(File srcDir,File desDir) throws IOException {  
    //过滤.java文件,找到源目录中的java文件  
    File[] fs = srcDir.listFiles(new FilenameFilter(){  

        public boolean accept(File dir,String name){  
            return new File(dir,name).isFile() && name.endsWith(".java");  
        }  

    });  

    //迭代所有文件,拷贝文件  
    for(File file:fs){  
        //创建流对象  
        InputStream in = new FileInputStream(file);  
        OutputStream out = new FileOutputStream(new File(desDir,file.getName().replaceAll(".java", ".txt")));  
        //file.getName().replaceAll(".java", ".txt"))-->file文件中的文件名中的".java",改成".txt"  

        //IO操作  
        byte[] buffer = new byte[1024];  
        int len = -1;  
        while((len = in.read(buffer)) != -1){  
            out.write(buffer);  
        }  

        in.close();  
        out.close();  
    }  

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值