ディレクトリ内のすべてのファイル内の特定の文字列を検索します。ディレクトリ内のすべてのファイルで文字列を検索します。
例:/テスト/章/私が試してみました
D:/test/chapters
/chapter1.log
/chapter2.log
/chapter3.log all these sub files under D:/test/chapters/ .
サンプルコード:
public class Example {
public Example() {
super();
}
public int plugin_execute() {
boolean foundstring=false;
try {
File dir = new File("D:/test/chapters");
String[] children = dir.list();
if (children == null) {
System.out.println("does not exist is not a directory");
} else {
for (int i = 0; i < children.length; i++) {
String filename = children[i];
System.out.println(filename);
if (filename !=null) {
foundstring = testString(filename, "tiger");
System.out.println("failed");
}
//Search for entry in file
if (!foundstring) {
return //failuremsg
} else {
System.out.println("failed");
return //succes
}
}
}
return 1;
} catch (Exception e) {
return //error mssg
}
}
private boolean teststring(String filePath, String str) {
BufferedReader br = null;
File file = new File(filePath);
boolean result = false;
if(!file.exists())
return false;
try {
br = new BufferedReader(new FileReader(filePath));
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
if (sCurrentLine.contains(str)) {
result = true;
System.out.println(str);
System.out.println("Found entry ");
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
}
それが唯一の最後のファイルの出力を返し、手段パスDの "虎" を検索します最後のファイルで成功を検索すると、それ以外の場合は成功します。 しかし、文字列が最初のファイルに見つかったら成功したい。つまり、第1章が...どのように私はこのコードを変更することができます示唆してください
....第1章では見つからなかった場合、それは第2章では、検索を続けるべき、成功を返す必要があり
チェックhttp://stackoverflow.com/questions/1844688/read-all-files-in-a-folder –
サイドノート - あなたは、Java 7を使用している場合は、[試す-で-リソース]を使用(https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) – 4castle
ディレクトリ内の文字列を検索したい – user092