今天向大家分享一段IO流代码,专门查找某个文件夹下的某种类型的文件,然后赋值到指定的文件夹下。因为小编今天在查看电脑文件的时候,一直点鼠标一个个找,文件夹路径少那还好,关键是想找的ppt文件分布在不同文件夹下,而且不同文件夹的嵌套数大不一样,这样一层一层文件夹点开找到PPT文件在复制粘贴出来太麻烦了,所以干脆写了段代码,自动搜索某路径下所有匹配的文件,然后调用文件复制的方法把文件都放大一个统一文件目录下,这样看起来一目了然,还方便;代码如下
package com.ibeifeng.main;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class findFiles {
public static void main(String[] args) throws IOException {
File fromFile = new File("D:\\BaiduNetdiskDownload");
File dir = new File("D:\\toFile");
judgeFile(fromFile, dir);
}
public static void copyFile(File fromFile, File toFile) throws IOException {
FileInputStream ins = new FileInputStream(fromFile);
FileOutputStream out = new FileOutputStream(toFile);
byte[] b = new byte[1024];
int n = 0;
while ((n = ins.read(b)) != -1) {
out.write(b, 0, n);
}
ins.close();
out.close();
}
public static void judgeFile(File file, File dir) throws IOException {
File[] files = file.listFiles();
for (File a : files) {
if (a.isDirectory()) {
judgeFile(a, dir);
} else if (a.getAbsolutePath().endsWith(".ppt")) {
String name = a.getName();
File toFile = new File(dir, name);
copyFile(a, toFile);
}
}
}
}