通过字符串搜索含有该字符串的文件本来应该事件很简单的事情,不过下面写的不过是多此一举的事情也是为了能了解一下文件的字节流,了解文件的编码方式写了点代码,感觉很普通
package com.gdin.dome;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import org.junit.Test;
public class dome3 {
@Test
public void fun(){
/*
* 获取到路径
*/
File dir = new File("C:/Users/Administrator/Desktop/新建文件夹");
/*
* 保存所有的文件
*/
File[] files = dir.listFiles();
/*
* 遍历文件
*/
for(File f : files){
if(f.isDirectory()){//判断是否为一个路径。是的话遍历该文件夹本身
//fun(f.getAbsolutePath());这里不做演示
System.out.println("dir ==> "+f.getAbsolutePath());
} else {
String filename = f.getAbsolutePath();
if(filename.endsWith(".docx") || filename.endsWith(".doc") || filename.endsWith(".txt")){//给定文件格式
/*
* 读取字符
*/
isContantChar(f, "a");
}
//System.out.println("filename ==> "+f.getAbsolutePath());
}
}
}
public void isContantChar(File f, String str){
try {
/*
* 得到编码方式
*/
String code = getCode(f);
InputStream input = new FileInputStream(f);
int temp =0;//保存当前得到的字节
int len = 0;//读取文件内容的计数器
int flag = 2;//根据编码类型设定,默认为utf-8,中文编码的字节数-1
if(code.equals("GBK")){
input.skip(0);//从第0个开始读
flag = 1;//GBK只需要两个
}else {
input.skip(3);//从第4个位置开始读
}
//根据编码方式将符号转化为16进制
//System.out.println(s);
String codestr = "";
for(int j = 0; j < str.length(); j++){
char c = str.charAt(j);//获取到当前字符
String s;//保存当前字符解析后的字符串
if(c <= 0x007E){//英文字符时
s = Integer.toHexString(c).toUpperCase();//转为16进制
codestr += s;
}else {
s=URLEncoder.encode(str.substring(j, j+1), code);//中文解码
String[] codeArray = s.split("%");
for(int i =0; i < codeArray.length; i++){
codestr += codeArray[i];
}
}
if(j < str.length()-1){
codestr += ",";//通过加上逗号来作为对比,以防多个字节时出现重叠
}
}
String text = "";
int into = 0;//用于判断是否进入连续下面的循环体
while((temp = input.read()) != -1){
/*
* 通过判断是否是英文符号
* into的用意为判断为中文时需要标志,当into为0时则当前的字节为英文字符的编码
*
*/
if(temp > 0x007E || into != 0){
//中文字符时,将连续的两个或者三个字节拼在一起,
text += Integer.toHexString(temp).toUpperCase();
if(into == flag){//
text = text+",";
into = 0;
} else {
into++;
}
} else {
text = text + Integer.toHexString(temp).toUpperCase()+",";
}
/
len++;
if(len+1 >= codestr.length()/2){//当当前读到的字节数目大于需要查找的字符串数时开始搜索
if(text.contains(codestr)){
//System.out.println(text);
System.out.println("包含有该字符段的文件有==>"+f.getAbsolutePath());
break;
}
}
}
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getCode(File f) throws IOException{
FileInputStream in = new FileInputStream(f);
BufferedInputStream bin = new BufferedInputStream(in);
int p = (bin.read() << 8) + bin.read();
String code = null;
switch (p) {
case 0xefbb:
code = "UTF-8";
break;
case 0xfffe:
code = "Unicode";
break;
case 0xfeff:
code = "UTF-16BE";
break;
default:
code = "GBK";
}
return code;
}
}
学习了很久才知道了所以编码的一些规则,本人智商有些,目前找不出其他方式比较好的方式搜索。