我正在查看文件名的日誌以及它們在指定日期上次修改的時間。其內容如下所示:對子串內的子串進行排序
(comment:file_02389.txt,lastmodified:Wed Oct 10 19:10:49)
(comment:file_02342.txt,lastmodified:Wed Oct 10 17:16:08)
(comment:file_02315.txt,lastmodified:Wed Oct 10 18:45:12)
(comment:file_02344.txt,lastmodified:Wed Oct 10 08:31:01)
日誌以單個字符串形式給出,沒有換行符。我想解析字符串來查找最近修改過的文件,即在這種情況下具有最新的日期file_02389.txt。每個「註釋」的字符長度是固定的,雖然假設將來可能會改變,並且如果同一個文件被多次修改,則文件名不會是唯一的。
是否有最可擴展/可維護的方法來查找最新的文件?執行時間和記憶不是重要的因素。主要的問題是初學者程序員可以理解和使用代碼。
我的第一個想法是將字符串拆分爲可以使用自定義比較器排序的列表。我認爲這是簡單的,但不能擴展:
{//given String log
...
//setup
List<String> temp = Arrays.asList(log.trim().split("\\(comment\\:")); //too complex for one line?
//the first entry is blank so it must be removed else a substring() call will fail
if(temp.get(0).equals(""))
temp.remove(0);
int period = full.get(0).indexOf('.');
int colon = full.get(0).indexOf(':');
//process
Collections.sort(temp, DATE);
return test.get(test.size()-1).substring(0, period)) //last entry is the most recent
}
public final Comparator<String> DATE = new Comparator<String>()
{
public int compare(String s1, String s2)
{
return s1.substring(28).compareTo(s2.substring(28));
}
};
它的工作原理,但使用依賴於該線長度和比較,這只是在這一個案例有用子。我不喜歡使用.split,然後不得不刪除第一個條目,但是我想避免一個真實而難以理解的正則表達式,如果這是一個替代方案。將日期視爲字符串而不是比較爲整數或日期對象似乎不合乎要求,但可節省代碼行。
我目前使用的排序映射避免創建一個隨機數字的一次性使用的比較器,但專門的映射看起來相當複雜,我試圖做的事情。我仍然認爲比爲文件名創建一個數組更好,另一個時間創建數組,然後複製時間三分之一,以便可以對時間數組進行排序,並將其最後一個值與副本中的相應索引進行比較。
{
...
//same setup as before
//process
//key is time, value is file name
SortedMap<String, String> map = new TreeMap<String, String>();
for(String s : temp)
map.put(s.substring(colon+1), s.substring(0, period));
//the value to which the last key is mapped is guaranteed to be the most recent file
return map.get(map.lastKey()); //too complex for one line?
}
在你的例子中10月10日是週一。和週三。 - 不可能...其次 - 你使用字符串比較來比較日期 - 這不應該工作。 – alfasin
我的錯字,改變週一至週三,謝謝。因爲日期被視爲字符串,所以比較起作用。 '10月10日19:10:49'週三大於'Wed Oct 10 17:16:08',因爲'9'大於'7'。顯然這隻有在格式一致並且不用於_how>或<日期時才適用。 – apcris
沒有。它會一直持續到你開始比較不同的日子。 W> T因此你會得到那個Wend。 >週四etc. – alfasin