在指定路径下的所有文件中查找给定的字符串

先简单说下File类

File类的对象主要用来获取文件本身的一些信息,如文件所在的目录、文件长度、文件读写权限等,不涉及对文件的读写操作

创建java.io.File的实例对象,可以通过java.io.File的构造方法public File(String pathname)来实现,其中pathname指定文件名或路径名

Java.io.File的成员方法

public boolean exists():判断当前对象表示的文件或路径是否存在

public boolean isFile(): 判断当前对象是否表示文件

public boolean isDirectory():判断指定的当前对象是否表示路径

public boolean canRead():判断当前对象表示的文件或路径是否可读

public boolean canWrite():判断当前对象表示的文件或路径是否可写

public boolean canExecute():判断当前对象是否表示可执行的文件

public boolean isHidden():判断当前对象表示的文件或路径是否具有隐藏属性

public boolean isAbsolute():判断当前对象的表示形式是否采用绝对路径的形式

public String getAbsolutePath():获取当前对象的绝对路径,以字符串的形式返回

public File getAbsoluteFile():获取当前对象的绝对路径,返回类型java.io.File

public long lastModified():获取最后修改的时间

public long length():获取当前对象表示的文件的长度

public String getName():获取当前对象表示的文件或路径的名称

public String getPath():获取当前对象表示的文件或路径的带路径名称

下面实现在指定路径下的所有文件中查找给定的字符串

import java.io.*;
public class cam1
{
	public static int mount = 0;
    public static void main(String[] args) 
    {
		String filename = "C:\\Users\\Administrator\\Desktop\\code";
		//创建一个 File 实例,表示路径名是指定路径参数的文件
		File file = new File(filename);
		if(args.length>0) //输入要查找的关键字
		{
			findFile(file, args[0]);
			print(args[0]);
		}
	}
    public static boolean isTrueFile(File file) 
    {
		if(!file.exists() || !file.canRead())
		return false;
		if (file.getName().startsWith("."))
		return false;
		if (file.getName().endsWith("."))
	    return false;
		return true;
	}
    public static void findFile(File file, String word) 
    {
		File[] listFiles = file.listFiles(); 
		//得到一个File数组,它默认是按文件最后修改日期排序的
		for (int i = 0; i < listFiles.length; i++) 
		{
		   if (listFiles[i].isDirectory())
		   findFile(listFiles[i], word);
		   else if (isTrueFile(listFiles[i]))
		   search(listFiles[i], word);
		}
	}
    public static void search(File file, String word) 
    {
		try 
		{
			int j = 0, k = 0, ch = 0;
			String str = null;
			FileReader in = new FileReader(file);
			while ((ch = in.read()) != -1) 
			{
				str += (char) ch;
			}
			if (str != null)
			{
				while (str.indexOf(word, j) != -1) 
				{
					k++;
					j = str.indexOf(word, j) + 1; // 返回第一次出现的指定子字符串在此字符串中的索引
				}
			}
			if (k > 0) 
			{
				System.out.println("在" + file.getAbsolutePath() + "有" + k+ "个关键字");
				mount++;
			}
			in.close();
		} 
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		} 
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
    public static void print(String word)
    {
		if (mount != 0) 
		{
			System.out.println("找到" + mount + "个文本包含关键字" + word + "!");
		} 
		else 
		{
			System.out.println("没有找到相应的文件");
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值