package com.heima.test;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
//文件过滤筛选拷贝:把指定目录下(不包含子目录)的所有图片,复制到另一个指定目录下(使用文件过滤器来过滤图片)
public class Lianxi2 {
public static void main(String[] args) throws IOException {
System.out.println("请输入指定复制源文件夹路径:");
File file1 = getFile();
System.out.println("请输入指定存放文件夹路径:");
File file2 = getFile();
//用一个集合来存放符合拷贝文件的绝对路径
List<File> list = new ArrayList<>();
//寻找所有符合条件的文件并将路径存入集合
seek(file1,list);
//从集合读取文件路径,复制到新的文件夹路径
copy(file2,list);
System.out.println("复制文件数量:"+list.size());
}
private static void copy(File file2, List<File> list) throws IOException {
if (!list.isEmpty()) {
BufferedInputStream bts = null;
BufferedOutputStream bos = null;
for (File file : list) {
bts = new BufferedInputStream(new FileInputStream(file));
bos = new BufferedOutputStream(new FileOutputStream(file2));
int x;
while((x = bts.read()) != -1) {
bos.write(x);
}
bos.flush();
}
bts.close();
bos.close();
}
}
private static void seek(File file1, List<File> list) {
File[] filelist = file1.listFiles();
if (filelist != null) {
for (File file : filelist) {
if (file.isFile()
&& (file.getName().endsWith(".jpg")
|| file.getName().endsWith(".png"))
) {
// System.out.println(file.getAbsolutePath());
list.add(file);
}else if (file.isDirectory()) {
seek(file,list);
}
}
}else{
System.out.println("文件夹下为空,请检查后输入!");
}
}
private static File getFile() {
Scanner sc = new Scanner(System.in);
while(true) {
String line = sc.nextLine();
File file = new File(line);
if (!file.isDirectory()) {
System.out.println("非文件夹路径,请重新输入:");
}else{
System.out.println("文件夹路径输入成功!");
return file;
}
}
}
}
|
|