在我的文件中,存在约 50 行字符串数据,这些数据以 1002
开头并以 1003
结尾进行分隔,例如:
1002target data A10034d8e
但是其中一个或两个分隔符可以分成多行,例如:
10
02target data B1003922510
02target data C10
033d0910
02target data D10033d09
如何仅打印文件中的分隔数据,不包括开始和结束分隔符?
我的代码是:
try {
File file = new File("new1.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
int lines = 0, b;
String seq = "";
while ((line = bufferedReader.readLine()) != null) {
lines++;
if (lines == 2) {
StringBuilder bulid = new StringBuilder(line);
bulid.delete(0, 2);
b = bulid.length();
bulid.delete(b - 8, b);
stringBuffer.append(bulid);
stringBuffer.append("\n");
lines = 0;
}
}
fileReader.close();
System.out.println("Contents of file:");
System.out.println(stringBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
但是此代码仅当数据和分隔符位于一行时才有效。
最佳答案
对于每一行:
搜索索引 1002,如果找到搜索索引 1003,则打印中间的内容。
int start = line.indexOf("1002");
if (start >= 0) {
int end = line.indexOf("1003", start);
if (end >= 0) {
String searched = line.substr(start + 4, end);
// Doing something with searched
}
} else {
// Not found
}
关于java - 检查字符串条件并使用 java 在文件中打印所需的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37700528/