这是一款整理笔记的小工具,日常学习中我们所接收到的一手文档,通常会包含各种类型(.jpg .png .drawio .txt)的文件。但在这个信息量居恐怖的时代,我们不可能完全记住所有知识,我们需要的只是在需要的时候如何快速检录已学知识,类似数据库的索引,我们也需要建立一个自己的认知体系数据库。
介于win文件查找的效率和效果,而且随时都带着自己的笔记本也不太实际。所以最好的方式是把自己的学习资料上传到云端,或是自己的服务器上,利用 linux 提供的命令(ag 或是 grep)进行文件内检索。
但你不可能所有文件都上传(大文件,隐私,各种图片或视频),这个时候你可能需要一款工具文件提取工具,先上代码:
// 1 M
static long M = 1048576L;
/**
*
* @param path 源文件目录
* @param toPathDir 目标文件目录
* @param sonPath 子路径,记录的源文件子目录相对路径,用来创建目标文件子目录
* @param needFileTypes 需要过滤的文件类型
* @param filterDirs 需要跳过的特殊目录
* @param maxSize 文件大小上限
* @throws IOException
*/
public static void copyMdFile(String path, String toPathDir, String sonPath, final String[] needFileTypes, String[] filterDirs, final long maxSize) throws IOException {
File dir = new File(path);
File[] files = dir.listFiles(new FileFilter() {
public boolean accept(File pathname) {
String end = pathname.getName();
boolean isTarget = false;
if (pathname.isDirectory())
isTarget = true;
else if (needFileTypes != null && needFileTypes.length > 0){
// 指定需要提取的文件类型
for (String suffix : needFileTypes){
if (end.endsWith(suffix)){
isTarget = true;
break;
}
}
if (isTarget){
// 过滤大于 2M 的txt文件
if (end.endsWith(".txt") && pathname.length() > M * 2)
isTarget = false;
// 过滤大于 10M 的文件
if (pathname.length() > maxSize)
isTarget = false;
}
}
return isTarget;
}
});
f:
for (File file : files){
if(file.isDirectory()){
String name = file.getName();
// 过滤特殊目录
for (String filerDir : filterDirs){
if (name.startsWith(filerDir))
continue f;
}
String sonPath1 = sonPath + "\\" + file.getName();
System.out.println(file.getName() + " : " + file.length());
// 当前为目录,递归
copyMdFile(file.getAbsolutePath(),
toPathDir, sonPath1, needFileTypes, filterDirs, maxSize);
}else{
// windows 下 '\' 要用 '\\\\'
// String[] split = file.getAbsolutePath().split("\\\\");
String toPath = toPathDir + sonPath;
File toPathFileDir = new File(toPath);
if (!toPathFileDir.exists()){
if(!toPathFileDir.mkdirs()) {
System.out.println("目录创建失败: " + toPath);
continue;
}
}
// copy file
java.nio.file.Files.copy(
file.toPath(),
toPathFileDir.toPath().resolve(file.getName())
);
}
}
}
测试:
public static void main(String[] args) {
String dirPath = "F:\\xxx\\oldDir";
String copy2Path = "F:\\xxx\\newDir\\";
// 需要提取的文件类型
String[] needFileType = {".md",".docx","pptx",".xlsx",".xmind",".png",".drawio"};
// 需要跳过的特殊目录
String[] filterDirectories = {"src","java","idea","data"};
// 文件最大为 10 M
long maxSize = M * 10;
try{
copyMdFile(dirPath,copy2Path, "", needFileType, filterDirectories, maxSize);
}catch (IOException e){
}
}
将 oldDir 目录中指定文件类型 needFileType 提取到 newDir 中。好了,就说这么多,祝各位策码奔腾!