2017-03-10 47 views
-3

LogParser.java的Java解析根據指定的字

package com.mpj.Parallelization; 

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.Scanner; 

public class LogParser { 

    public static void main(String[] args) throws Exception { 

     File logfile = new File("/C:/ParallelKMeansProject/logs/log.txt"); 

     try { 
      Scanner parserscanner = new Scanner(logfile); 

      String nextLine = parserscanner.nextLine(); 

      String[] logcomponent = nextLine.split(" "); 

      String latitude = logcomponent[0]; 
      String longtitude = logcomponent[1]; 

      System.out.println(latitude); 
      System.out.println(longtitude); 

      System.out.println("Next Line: " + nextLine); 

     } catch (FileNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

    } 

} 

log.txt的內容

2017年3月10日12時30分30秒DEBUG SerialKMeans:29 -

======

迭代次數:21 W平方誤差ithin簇總和: 13.902870732812898

初始起點(隨機):

羣集0:41.051205,28.808497羣集1:41.055391,28.785407羣集 2:41.054838,28.802617羣集3:41.022421,28.788169羣集4: 41.024494,28.784099羣集5:41.018659,28.787669羣集6:平均值/模式全局替換41.040879,28.753359

缺失值...

這就像,我有log.txt和日誌並排寫長。

我的第一個問題是System.out.println("Next Line: " + nextLine);

我沒有看到所有的日誌使用此命令行。日誌寫入在這裏結束(2017-03-10 12:30:30 DEBUG SerialKMeans:29 - )不寫更多.Logos全部寫在txt文件中。不是底線。但它只寫2017-03-10 12:30:30 DEBUG SerialKMeans:29 -

我的第二個問題;如果我們解決了第一個問題,我想解析一個特定的單詞。我怎樣才能做到這一點

+0

你只能讀一行'String nextLine = parserscanner.nextLine();'。你應該循環讀取每一行 – AxelH

+1

使用這個來獲得所有行'while(parserscanner.hasNextLine()){nextLine = parserscanner.nextLine(); }',爲了解析特定的模式,你可以使用掃描器的findInLine方法或者直接使用string.split –

回答

0

我建議做這樣的事情:

FileInputStream stream = new FileInputStream(logfile); 
    BufferedReader br = new BufferedReader(new InputStreamReader(stream)); 

    String line; 

    while ((line = br.readLine()) != null) { 
     System.out.println (line); 
    } 

或者,如果你想保持你當前的代碼,我會怎麼做@奧馬爾埃爾登建議,使用while循環遍歷所有行。