指定したサフィックスを持つファイルを単一レベルのフォルダーにコピーし、ファイルの名前を変更します

アイデア:最初に、元のフォルダーの要件を満たすファイルを除外し、これらのファイルをターゲットフォルダーにコピーして名前を変更します。

見つかった:多くのブロガーは、指定されたサフィックスを持つファイルをフィルターを介して元のフォルダーからフィルターで除外し、拡張forループを記述して、これらのファイルをターゲットフォルダーにコピーします。このようなコードは、次の方法1で実行されます見せて。しかし実際には、listFiles()メソッドをフィルターとして使用すると、Fileオブジェクト自体がトラバースされるため、拡張されたforループを使用しなくても、フィルタリング後に直接コピーできます。このようなコードは、次のメソッド2になります。表示する。

方法1:

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("拷贝完成");
}

方法2:

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