2 回答
TA贡献1829条经验 获得超6个赞
“当您找到任何匹配项时,您可以将结果放入数组/列表的字符串中。您可以返回列表/数组中的最后一个元素”;
String searchWord = "asiana";
List<String> list = new LinkedList<String>();
try (BufferedReader in = new BufferedReader(
new FileReader("D:\\Downloads\\dataAnalysis1.txt"));
BufferedWriter out = new BufferedWriter(
new FileWriter("D:\\Downloads\\output.txt"))) {
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
// extract by lines and write to file
if (line.contains(searchWord)) {
out.write(line);
list.addLast(line);
out.newLine();
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
//print the last element from the list.
print: list.get(list.size()-1);
TA贡献1820条经验 获得超9个赞
如我所说
如果它是 CSV,那么你有一些分隔符(, or ;),当你阅读文件时,你已经在 line 变量中获取了整行,你可以使用 String.split 然后参考新数组上的 .length ,你将获得,那应该给你最后一列的值
但请注意,正如 M. Prokhorov 所提到的,如果数据也包含转义分隔符,那么它将无法正常工作,这取决于数据
public static String getLastColumnValue(String value, char separator) {
//https://stackoverflow.com/questions/54630596/how-to-retrieve-last-column-from-set-of-data
String[] tokens = value.split(String.valueOf(separator));
//indexed from zero -> length -1
if(tokens.length>0) {
return tokens[tokens.length-1];
}else {
return null;
}
}
有测试
System.out.println(StringUtils.getLastColumnValue("first col;second;foo;fooolastsemicol", ';'));
//fooolastsemicol
System.out.println(StringUtils.getLastColumnValue("first col,second,foo,fooolastcomma", ','));
//fooolastcomma
添加回答
举报
