在Java中,可以使用以下几种方法来在文本文件中查找字符串:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileSearch {
public static void main(String[] args) {
String filePath = "path/to/file.txt";
String targetString = "search string";
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
if (line.contains(targetString)) {
System.out.println("Found in line: " + line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileSearch {
public static void main(String[] args) {
String filePath = "path/to/file.txt";
String targetString = "search string";
try {
Scanner scanner = new Scanner(new File(filePath));
int lineNumber = 1;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.contains(targetString)) {
System.out.println("Found in line " + lineNumber + ": " + line);
}
lineNumber++;
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
首先,确保已将Apache Commons IO库添加到项目的依赖中。然后,可以使用FileUtils类的readLines()方法读取文件内容,并使用StringUtils类的containsIgnoreCase()方法来判断每一行是否包含目标字符串。
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class FileSearch {
public static void main(String[] args) {
String filePath = "path/to/file.txt";
String targetString = "search string";
try {
List<String> lines = FileUtils.readLines(new File(filePath), "UTF-8");
for (int i = 0; i < lines.size(); i++) {
String line = lines.get(i);
if (StringUtils.containsIgnoreCase(line, targetString)) {
System.out.println("Found in line " + (i + 1) + ": " + line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
这些方法可以帮助您在文本文件中查找字符串。根据文件大小和性能要求,您可以选择适合您需求的方法。
领取专属 10元无门槛券
手把手带您无忧上云