Raw File IO
这种方法没有考虑到任何XML标记或任何东西。 它只是对档案中所含的某种扼杀进行检查。
你们必须采取的基本步骤是使用光线文件:
- Loop through the files in
listOfFiles
- Open each file (see
FileReader
and BufferedReader
)
- Read the content (e.g. line by line with
readLine
)
- Check if your string is in the read content
- If yes, output the file s name and continue with next file
或以最低代码表示:
// In looping through files:
// Step 2:
BufferedReader r = new BufferedReader(new FileReader(f));
// Step 3:
String s = r.readLine();
while (s != null) {
// Step 4:
if (s.contains("TestString")) {
// Step 5:
System.out.println(f.getAbsolutePath());
break;
}
s = r.readLine();
}
r.close();
请注意,如果你扼杀有线性的话,这就赢得了工作。
SAX2
SAX是一种面向上游的XML教区标准,其行文为XML,如果某一要素开始、案文找到等,则向手提退。 您可以利用这一方法核对《国际禁止杀伤人员地雷公约》的案文内容,并且还执行一部国家文书,如果文本确实在<代码>和“t”中碰到,则跟踪该文本;要素,但这是一个比较复杂的问题。
This is what to do using a SAX2 implementation:
- Implement the
ContentHandler
SAX interface in your class
- In that content handler, implement the
characters
method to check for your string
- Create a reader with
XMLReaderFactory.createXMLReader()
- Set your content handler with
setContentHandler
on the reader
- Call
parse
on the reader with an InputSource
for your file
DOM
DOM is a standard XML model that builds a tree of the nodes in memory that can be traversed. This method is really simple to use:
- Parse the XML into a DOM using
DocumentBuilder
- Get all
<string>
elements using getElementsByTagName
- Check if their values equal your test string using
getNodeValue
Code:
Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(f);
NodeList l = d.getElementsByTagName("string");
for (int i = 0; i < l.getLength(); ++i) {
if ("TestString".equals(l.item(i).getNodeValue())) {
System.out.println(f.getAbsolutePath());
break;
}
}
希望这一帮助。