从指定文件中找出字符串“HikVison BLE”所在的行,然后查找此行的前面和后面最近的空行分别是哪两行,将这两行之间的所有字符复制到其他文件中。使用java
时间: 2024-04-29 18:26:22 浏览: 76
可以使用以下代码来实现:
```
import java.io.*;
public class FindString {
public static void main(String[] args) {
String inputFile = "input.txt";
String outputFile = "output.txt";
String targetString = "HikVison BLE";
int beforeLine = 0;
int afterLine = 0;
boolean found = false;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile)));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
String line;
int lineNumber = 0;
while ((line = reader.readLine()) != null) {
lineNumber++;
if (line.contains(targetString)) {
found = true;
System.out.println("Found target string on line " + lineNumber);
beforeLine = findPreviousEmptyLine(reader, lineNumber);
afterLine = findNextEmptyLine(reader, lineNumber);
if (beforeLine != -1 && afterLine != -1) {
writer.write("Lines " + (beforeLine + 1) + " to " + (afterLine - 1) + ":\n");
reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile)));
for (int i = 1; i <= afterLine; i++) {
line = reader.readLine();
if (i > beforeLine && i < afterLine) {
writer.write(line + "\n");
}
}
} else {
System.out.println("Could not find empty lines");
}
break;
}
}
if (!found) {
System.out.println("Target string not found");
}
reader.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static int findPreviousEmptyLine(BufferedReader reader, int currentLine) throws IOException {
String line;
int lineNumber = currentLine - 1;
while (lineNumber >= 1) {
line = reader.readLine();
if (line.equals("")) {
return lineNumber;
}
lineNumber--;
}
return -1;
}
public static int findNextEmptyLine(BufferedReader reader, int currentLine) throws IOException {
String line;
int lineNumber = currentLine;
while ((line = reader.readLine()) != null) {
lineNumber++;
if (line.equals("")) {
return lineNumber;
}
}
return -1;
}
}
```
请将输入文件的名称替换为你的实际文件名称,然后运行该程序即可。找到的结果将被保存在输出文件中。
阅读全文