Java程序之检索文件方式(含内容)
项目说明
给定一个指定目录和关键字,扫描其中的文件名和文件内容,找到包含关键字的文件
完整代码
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
public class demo4 {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入要扫描的路径");
File rootDir = new File(scanner.next());
System.out.println("请输入要查询的词");
String toFind = scanner.next();
scanDir(rootDir,toFind);
}
private static void scanDir(File rootDir, String toFind) throws IOException {
File[] files = rootDir.listFiles();
if(files == null){
return;
}
for (File f:files) {
if(f.isDirectory()){
scanDir(f,toFind);
} else checkFile(f,toFind);
}
}
private static void checkFile(File f, String toFind) throws IOException {
if(f.getName().contains(toFind)){
System.out.println("该文件名中包含关键词:" + f.getCanonicalPath());
}
try(InputStream inputStream = new FileInputStream(f)){
Scanner scanner = new Scanner(inputStream);
StringBuilder stringBuilder = new StringBuilder();
while(scanner.hasNextLine()){
stringBuilder.append(scanner.nextLine() + "\n");
}
if(stringBuilder.indexOf(toFind) > -1){
System.out.println("该文件内容包含关键字: " + f.getCanonicalPath());
}
}
}
}
核心代码
private static void scanDir(File rootDir, String toFind) throws IOException {
File[] files = rootDir.listFiles();
if(files == null){
return;
}
for (File f:files) {
if(f.isDirectory()){
scanDir(f,toFind);
} else checkFile(f,toFind);
}
}
传入一个文件对象和关键字字符串。通过调用listFiles方法,如果文件对象是空,代表该路径下没有任何文件或目录,那么就返回上级目录,否则就将所有该路径下的文件或目录都存储在File数组中,并依次便利,如果是目录,就再次递归,找该目录下的文件,如果是文件,就比较文件名和文件内容中有没有包含关键字
private static void checkFile(File f, String toFind) throws IOException {
if(f.getName().contains(toFind)){
System.out.println("该文件名中包含关键词:" + f.getCanonicalPath());
}
try(InputStream inputStream = new FileInputStream(f)){
Scanner scanner = new Scanner(inputStream);
StringBuilder stringBuilder = new StringBuilder();
while(scanner.hasNextLine()){
stringBuilder.append(scanner.nextLine() + "\n");
}
if(stringBuilder.indexOf(toFind) > -1){
System.out.println("该文件内容包含关键字: " + f.getCanonicalPath());
}
}
}
先比较文件名中有没有包含关键字,再通过FileInputStream读取文件中全部内容,将所有的内容写成一个字符串,并比较字符串中是否包含关键字
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Spring boot项目redisTemplate实现轻量级消息队列的方法
这篇文章主要给大家介绍了关于Spring boot项目redisTemplate实现轻量级消息队列的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用Spring boot具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧2019-04-04
详谈HashMap和ConcurrentHashMap的区别(HashMap的底层源码)
下面小编就为大家带来一篇详谈HashMap和ConcurrentHashMap的区别(HashMap的底层源码)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧2017-08-08
使用Apache POI在Java中实现Excel单元格的合并
在日常工作中,Excel是一个不可或缺的工具,尤其是在处理大量数据时,本文将介绍如何使用 Apache POI 库在 Java 中实现 Excel 单元格的合并,需要的可以了解下2025-03-03


最新评论