Copie el archivo con el sufijo especificado en la carpeta de un solo nivel y cambie el nombre del archivo

Idea: Primero, filtre los archivos que cumplen con los requisitos en la carpeta original, y luego copie estos archivos en la carpeta de destino y cámbieles el nombre.

Encontrado: muchos bloggers filtran los archivos con el sufijo especificado de la carpeta original a través del filtro y luego escriben un bucle mejorado para copiar estos archivos en la carpeta de destino. Dicho código se llevará a cabo en el siguiente método uno Mostrar Pero, de hecho, sabemos que cuando se usa el método listFiles () como filtro, se ha atravesado el objeto File, por lo que se puede copiar directamente después del filtrado, sin la ayuda de un bucle for mejorado, dicho código estará en el siguiente método dos Para mostrar.

Método uno:

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

Método dos:

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

 

Publicado 4 artículos originales · recibido 1 · vistas 187

Supongo que te gusta

Origin blog.csdn.net/joeychiang/article/details/105470054
Recomendado
Clasificación