2 回答

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超6個(gè)贊
“當(dāng)您找到任何匹配項(xiàng)時(shí),您可以將結(jié)果放入數(shù)組/列表的字符串中。您可以返回列表/數(shù)組中的最后一個(gè)元素”;
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貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超9個(gè)贊
如我所說
如果它是 CSV,那么你有一些分隔符(, or ;),當(dāng)你閱讀文件時(shí),你已經(jīng)在 line 變量中獲取了整行,你可以使用 String.split 然后參考新數(shù)組上的 .length ,你將獲得,那應(yīng)該給你最后一列的值
但請注意,正如 M. Prokhorov 所提到的,如果數(shù)據(jù)也包含轉(zhuǎn)義分隔符,那么它將無法正常工作,這取決于數(shù)據(jù)
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
添加回答
舉報(bào)