我有一个名为“Sample.text”的文本文件。它包含多行。从这个文件,我有搜索特定的字符串。如果凝视匹配或在该文件中找到,我需要打印整行。搜索字符串位于行的中间。我也在使用字符串缓冲区在从文本文件中读取字符串后追加字符串。此外,文本文件太大了。所以我不想逐行迭代。怎么做
答案 0 :(得分:6)
您可以使用Apache Commons IO
中的FileUtils来完成此操作小样本:
StringBuffer myStringBuffer = new StringBuffer();
List lines = FileUtils.readLines(new File("/tmp/myFile.txt"), "UTF-8");
for (Object line : lines) {
if (String.valueOf(line).contains("something")) {
myStringBuffer.append(String.valueOf(line));
}
}
答案 1 :(得分:0)
我们也可以使用正则表达式从文件中进行字符串或模式匹配。
示例代码:
import java.util.regex.*;
import java.io.*;
/**
* Print all the strings that match a given pattern from a file.
*/
public class ReaderIter {
public static void main(String[] args) throws IOException {
// The RE pattern
Pattern patt = Pattern.compile("[A-Za-z][a-z]+");
// A FileReader (see the I/O chapter)
BufferedReader r = new BufferedReader(new FileReader("file.txt"));
// For each line of input, try matching in it.
String line;
while ((line = r.readLine()) != null) {
// For each match in the line, extract and print it.
Matcher m = patt.matcher(line);
while (m.find()) {
// Simplest method:
// System.out.println(m.group(0));
// Get the starting position of the text
int start = m.start(0);
// Get ending position
int end = m.end(0);
// Print whatever matched.
// Use CharacterIterator.substring(offset, end);
System.out.println(line.substring(start, end));
}
}
}
}