2017-07-03 132 views
0

我在這裏有一個代碼,它接受一個文件的輸入,並且只顯示包含單詞「LANTALK」的特定行到控制檯,然後它將這些行寫出到外部文件。我需要的是能夠過濾行內的信息以某種方式顯示。解析一個日誌文件爲XML

下面是完整的代碼:

import java.io.*; 
import java.util.*; 

public class baseline 
{ 

    // Class level variables 
    static Scanner sc = new Scanner(System.in); 

    public static void main(String[] args) throws IOException, 
    FileNotFoundException { // Start of main 

    // Variables 
    String filename; 

    // Connecting to the output file with a buffer 
    PrintWriter outFile = new PrintWriter(
          new BufferedWriter(
          new FileWriter("chatOutput.log"))); 

    // Get the input file 
    System.out.print("Please enter full name of the file: "); 
    filename = sc.next(); 

    // Assign the name of the input file to a file object 
    File log = new File(filename); 
    String textLine = null; // Null 
    String outLine = ""; // Null 
    BufferedWriter bw = null; 



    try 
    { 
    // assigns the input file to a filereader object 
    BufferedReader infile = new BufferedReader(new FileReader(log)); 

     sc = new Scanner(log); 
      while(sc.hasNext()) 
      { 
       String line=sc.nextLine(); 
       if(line.contains("LANTALK")) 
        System.out.println(line); 
      } // End of while 


    try 
    { 
    // Read data from the input file 
    while((textLine = infile.readLine()) != null) 
    { 
     // Print to output file 
     outLine = textLine; 
     sc = new Scanner (outLine); 
      while(sc.hasNext()) 
      { 
       String line=sc.nextLine(); 
       if(line.contains("LANTALK")) 
       outFile.printf("%s\n",outLine); 
      }// end of while 
     } // end of while 
    } // end of try 


    finally // This gets executed even when an exception is thrown 
     { 
    infile.close(); 
    outFile.close(); 
     } // End of finally 
    } // End of try 


    catch (FileNotFoundException nf) // Goes with first try 
    { 
    System.out.println("The file \""+log+"\" was not found"); 
    } // End of catch 
    catch (IOException ioex) // Goes with second try 
    { 
    System.out.println("Error reading the file"); 
    } // End of catch 

    } // end of main 

} // end of class 

這裏是輸入文件的樣本行:

08:25:26.668 [D] [T:000FF4] [F:LANTALK2C] <CMD>LANMSG</CMD> 
<MBXID>1124</MBXID><MBXTO>5760</MBXTO><SUBTEXT>LanTalk</SUBTEXT><MOBILEADDR> 
</MOBILEADDR><LAP>0</LAP><SMS>0</SMS><MSGTEXT>but didn't give me the info I 
needed</MSGTEXT> 
08:25:26.672 [+] [T:000FF4] [S:1:1:1124:5607:5] LANMSG [0/2 | 0] 

,這裏是什麼,我試圖讓輸出看起來像:

8:25:00 AM [Steve Jobs] to [John Smith] but didn't give me the info I needed 

有沒有人有最好的方法來做到這一點的任何建議?我正在考慮某種XML解析器,但正在讀取的文件是.log,並且我不確定如何在此實例中將其轉換,因爲它已被讀取。謝謝!

回答

1

您需要一種混合方法:從緩衝讀取器中讀取具有LANTALK的行,然後從第一個<到最後一個>的字符串構建器中存儲。之後jsoup可以從這裏

https://mvnrepository.com/artifact/org.jsoup/jsoup/1.8.3

然後在if塊只是字符串的indexOf和lastIndexOf發揮您已經閱讀直到做XML技巧爲你

編輯

下載jsoup日誌行中的xml(將其放入字符串生成器中)

+0

好的。你碰巧有什麼樣的例子嗎?是jsoup像我需要下載的Java資源包? –