复制单级文件夹中指定后缀的文件并给文件重新命名

思路:首先要筛选出原文件夹中符合要求的文件,然后将这些文件复制到目标文件夹中并重新命名。

发现:很多博客通过过滤器从原文件夹中筛选出了指定后缀的文件后,又写了一个增强for循环来将这些文件拷贝到目标文件夹中,此类代码将在下面的方法一中进行展示。但其实我们知道,使用listFiles()方法做过滤器的时候,本身已经对File对象进行了遍历,因此过滤后就可以直接拷贝,不需要借助增强for循环,此类代码将在下面的方法二中进行展示。

方法一:

public static void main(String[] args) {
    copySingleFolder("d:/pic2/a/","d:/pic",".jpg");
}
	
public static void copySingleFolder(String destPath,String srcPath,String suffix) {
    //把两个文件路径转成文件对象并创建目标文件夹
    File srcFile = new File(srcPath);
    File destFile = new File(destPath);
    destFile.mkdirs();
    //通过过滤器筛选原文件夹中指定后缀的文件
    File[] listFiles = srcFile.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return new File(dir,name).isFile()?name.endsWith(suffix):false;
	}		
    });
    //拷贝前通过增强for循环对筛选后的文件进行遍历
    if(listFiles!=null && listFiles.length>0) {
        for(File f:listFiles) {
    //通过字节缓冲流进行拷贝并重新命名(也可以将其封装成静态方法然后直接调用)
            try(
                    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f.getAbsolutePath()));
                    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destPath+System.nanoTime()+".jpg"));
						) {
	        byte[] bs = new byte[1024];
		int len;
		while((len=bis.read(bs))!=-1) {
		    bos.write(bs,0,len);
		}
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
        }		
    }
    System.out.println("拷贝完成");
}

方法二:

public static void main(String[] args) {
    copySingleFolder("d:/pic1/a/","d:/pic",".jpg");
}
	
public static void copySingleFolder(String destPath,String srcPath,String suffix) {
    //把两个文件路径转成文件对象并创建目标文件夹
    File srcFile = new File(srcPath);
    File destFile = new File(destPath);
    destFile.mkdirs();
    //通过过滤器筛选原文件夹中指定后缀的文件
    File[] listFiles = srcFile.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
	    File f = new File(dir,name);
	    if(f.isFile()) {
	        if(name.endsWith(suffix)) {
    //通过字节缓冲流进行拷贝并重新命名(也可以将其封装成静态方法然后直接调用)
		    try(
		            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f.getAbsolutePath()));
		            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destPath+System.nanoTime()+".jpg"));
		            ){
		        byte[] bs = new byte[1024];
			int len;
			while((len=bis.read(bs))!=-1) {
			    bos.write(bs,0,len);
			}
		    } catch (IOException e) {
			e.printStackTrace();
		    }
		    return true;
		}
	    }
	    return false;
	}
			
    });
    System.out.println("拷贝完成");	
}
发布了4 篇原创文章 · 获赞 1 · 访问量 187

猜你喜欢

转载自blog.csdn.net/joeychiang/article/details/105470054