java 如何删除整行
删除整行的实现方法
在Java中删除整行通常涉及字符串处理或文件操作,以下是几种常见场景的实现方式:
字符串处理场景
使用String的replaceAll()方法配合正则表达式删除空行或特定行:

String text = "Line1\nLine2\n\nLine4";
text = text.replaceAll("(?m)^\\s*$[\n\r]*", ""); // 删除所有空行
删除包含特定内容的行:

String text = "Apple\nBanana\nOrange";
text = text.replaceAll("(?m)^Banana$\n?", ""); // 删除包含"Banana"的行
文件处理场景
使用BufferedReader和BufferedWriter逐行处理文件:
Path inputPath = Paths.get("input.txt");
Path outputPath = Paths.get("output.txt");
try (BufferedReader reader = Files.newBufferedReader(inputPath);
BufferedWriter writer = Files.newBufferedWriter(outputPath)) {
String line;
while ((line = reader.readLine()) != null) {
if (!line.trim().isEmpty()) { // 跳过空行
writer.write(line + System.lineSeparator());
}
}
}
使用Java 8 Stream API
更简洁的流式处理方式:
List<String> lines = Files.lines(Paths.get("input.txt"))
.filter(line -> !line.trim().isEmpty()) // 过滤条件
.collect(Collectors.toList());
Files.write(Paths.get("output.txt"), lines);
正则表达式说明
(?m)启用多行模式(^和$匹配每行的开始和结束)^\\s*$匹配空白行(包含零或多个空白字符的行)[\n\r]*匹配行尾的换行符
注意处理文件时应考虑异常处理和资源关闭,使用try-with-resources语句可自动管理资源。






