2015-07-03 41 views
0

我在這裏要做的是處理一個日誌文件,在我的情況下它是魷魚的access.log。我想讓我的程序看看文件中的第一個「單詞」,這是訪問URL時的Unix格式的時間。在程序的其他部分,我設計了一個時間類,它可以獲得程序最後一次在Unix時間運行的時間,並且我想將這段時間與文件中的第一個單詞進行比較,這恰好是Unix時間。基於第一個詞省略數組中的元素

我對如何做到這一點的初步思考是,我處理文件,將其存儲在數組中,然後基於文件中的第一個單詞,通過從處理文件所在的數組中刪除它,省略這些行,並把它放在另一個陣列

這是我到目前爲止。我非常確定自己很接近,但這是我第一次完成文件處理,所以我不完全知道我在這裏做什麼。

private void readFile(File file) throws FileNotFoundException, IOException{ 
    String[] lines = new String[getLineCount(file)]; 
    Long unixTime = time.getUnixLastRun(); 


    String[] removedTime = new String[getLineCount(file)]; 


    try(BufferedReader br = new BufferedReader(new FileReader(file))) { 
     int i = 0; 
     for(String line; (line = br.readLine()) != null; i++) { 
      lines[i] = line; 

     } 
    } 

    for(String arr: lines){ 
     System.out.println(arr); 
    } 
} 
+0

你想比較每一行的時間嗎?假設你的文件中有100行,這100行是否有時間作爲第一行的單詞?我只是有點困惑。 – Sneh

+0

@Sneh是啊。這是完全正確的。日誌中的每一行都以相同的方式開始 - 使用Unix時間。我想比較日誌中的UNIX時間並忽略舊條目。該程序知道它最後一次運行的時間,在unix中。 – iHateSigningUp

回答

1
private void readFile(File file) { 
    List<String> lines = new ArrayList<String>(); 
    List<String> firstWord = new ArrayList<String>(); 
    try (BufferedReader br = new BufferedReader(new FileReader(file))) { 
     String sCurrentLine; 
     while ((sCurrentLine = br.readLine()) != null) { 
      // Adds the entire first line 
      lines.add(sCurrentLine); 
      // Adds the first word 
      firstWord.add(sCurrentLine.split(" ")[0]); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

如果你願意,你可以用你的陣列。

1
private void readFile(File file) throws FileNotFoundException, IOException { 
     String[] lines = new String[getLineCount(file)]; 
     Long unixTime = time.getUnixLastRun(); 

     String[] removedTime = new String[getLineCount(file)]; 

     try (BufferedReader br = new BufferedReader(new FileReader(file))) { 
      int i = 0; 
      for (String line; (line = br.readLine()) != null; i++) { 
       lines[i] = line; 
      } 
     } 

     ArrayList<String> logsToBeUsed = new ArrayList<String>(); 

     for (String arr : lines) { 
      //Gets the first word from the line and compares it with the current unix time, if it is >= unix time 
      //then we add it to the list of Strings to be used 
      try{ 
       if(Long.parseLong(getFirstWord(arr)) >= unixTime){ 
        logsToBeUsed.add(arr); 
       } 
      }catch(NumberFormatException nfe){ 
       //Means the first word was not a float, do something here 
      } 
     } 
    } 

    private String getFirstWord(String text) { 
     if (text.indexOf(' ') > -1) { 
      return text.substring(0, text.indexOf(' ')); 
     } else { 
      return text; 
     } 
    } 

這是根據您發佈的代碼的答案。這可以更有效地完成,因爲您可以使用ArrayList存儲文件中的行,而不是在打開文件兩次時首先讀取行號getLineCount(file)。在for循環中,您一次又一次地聲明String對象。

相關問題