java 如何查找内容
查找字符串内容
使用 String 类的 contains() 方法检查字符串是否包含目标子串:
String text = "Hello, world!";
boolean found = text.contains("world"); // 返回 true
使用 indexOf() 获取子串的起始位置(未找到返回 -1):
int position = text.indexOf("world"); // 返回 7
查找数组或集合元素
通过循环遍历数组查找目标值:

int[] numbers = {1, 2, 3, 4};
int target = 3;
for (int num : numbers) {
if (num == target) {
System.out.println("Found");
break;
}
}
使用 List 的 contains() 方法:
List<Integer> list = Arrays.asList(1, 2, 3);
boolean exists = list.contains(2); // 返回 true
使用正则表达式匹配
通过 Pattern 和 Matcher 类进行复杂模式匹配:

Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("abc123");
boolean matches = matcher.find(); // 返回 true
文件内容查找
逐行读取文件并检查内容:
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.contains("target")) {
System.out.println("Found in line: " + line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
数据库查询
使用 JDBC 执行 SQL 查询:
String sql = "SELECT * FROM users WHERE name LIKE ?";
try (Connection conn = DriverManager.getConnection(url);
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, "%John%");
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
使用 Stream API
在集合中通过流式操作过滤数据:
List<String> items = Arrays.asList("apple", "banana", "cherry");
List<String> result = items.stream()
.filter(item -> item.startsWith("a"))
.collect(Collectors.toList()); // 结果: ["apple"]






