2017-07-03 93 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资源包? –