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
添加回答
舉報
