【发布时间】:2022-01-14 03:30:45
【问题描述】:
我有一个 .txt 文件,我通过 bufferReader 浏览,我需要从这个字符串中提取最后一个字符,我留下下面的行
<path
action="m"
text-mod="true"
mods="true"
kind="file">branches/RO/2021Align01/CO/DGSIG-DAO/src/main/java/eu/ca/co/vo/CsoorspeWsVo.java</path>
我有以下代码将我的整行代码设置在一个列表中,但我只需要它 Cs00rspeWsVo
while ((line = bufferdReader.readLine()) != null) {
Excel4 excel4 = new Excel4();
if (line.contains("</path>")) {
int index1 = line.indexOf(">");
int index2 = line.lastIndexOf("<");
line = line.substring(index1, index2);
excel4.setName(line);
listExcel4.add(excel4);
}
}
我只想从这里提取 Cs00rspeWsVo。 谁能帮我?谢谢
【问题讨论】:
-
您发送的代码未编译,它在
index2行缺少一个分号。请确保发布正确的代码并仔细检查没有其他问题。 -
您的代码中的具体问题是您在
if块的范围内声明int index1,然后尝试在if 之外引用它。也就是说,像这样处理 XML-ish 数据不一定是最好的方法:正确解析它以提取数据。 -
你的所作所为很老套,但老实说,如果你已经采用这种方法,为什么不直接搜索
/的倒数第二个索引,然后在那里提取。所以从第二个到最后一个/到最后一个<的子串,然后你就有了。int lastSlash = text.lastIndexOf("/"),然后是int secondToLastSlash = text.lastIndexOf("/", lastSlash),然后是你现有的index2,你有text.substring(secondToLastSlash, index2)。或者使用您当前的line,只需line.substring(line.lastIndexOf("/"))。 -
我建议从最后一个'/'到最后一个'c'的子字符串,或者使用正则表达式。
-
您也可以将路径解释为
Path,然后使用其高级方法。所以像Path.of(line).getFileName()或类似的东西。