在java中,当字符串匹配时,如何打印文件中的整行
我有一个名为Sample.text的文本文件。它包含多行。从这个文件中,我搜索了特定的字符串。如果在该文件中找到匹配的字符串,我需要打印整行。搜索字符串位于行的中间。另外,在从文本文件读取字符串后,我使用字符串缓冲区追加字符串。此外,文本文件太大。因此我不想逐行迭代。如何做到这一点您可以使用 小样本:在java中,当字符串匹配时,如何打印文件中的整行,java,Java,我有一个名为Sample.text的文本文件。它包含多行。从这个文件中,我搜索了特定的字符串。如果在该文件中找到匹配的字符串,我需要打印整行。搜索字符串位于行的中间。另外,在从文本文件读取字符串后,我使用字符串缓冲区追加字符串。此外,文本文件太大。因此我不想逐行迭代。如何做到这一点您可以使用 小样本: StringBuffer myStringBuffer = new StringBuffer(); List lines = FileUtils.readLines(new Fil
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));
}
}
我们还可以使用正则表达式从文件中进行字符串或模式匹配 示例代码:
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));
}
}
}
}
我试过使用子字符串。但是它没有返回正确的值。请看这个问题:谢谢你的回答。搜索字符串位于行的中间。此外,我正在使用字符串缓冲区在从文本文件读取字符串后追加字符串。此外,文本文件太大。因此,我不想逐行迭代。从这个问题上,我怀疑他想知道字符串是否包含在该行中。也许你想用contains切换startsWith。