在java中读取日志文件

smy*_*dsh 1 java fileinputstream logfile

是否可以使用java读取日志文件(abc.log)?

我想从我的日志文件中获取特定的字符串.

假设这是我的日志文件的内容.我只想要时间戳(例如:05:08:37)并将其打印到控制台.

2012-12-16 05:08:37,905 [Thread-1] INFO  com.submit.SubmitService - Wait time 500

2012-12-16 05:08:38,444 [Thread-1] INFO  com.submit.SubmitService - NO OF  RECORDS TILL NOW 3755    TOTAL TIME -- << 539

2012-12-16 05:08:38,668 [Thread-1] INFO  com.submit.SubmitService - Active Connection:: -69076

2012-12-16 05:08:38,670 [Thread-1] INFO  com.submit.SubmitService - Active Connection:: -65764
Run Code Online (Sandbox Code Playgroud)

Luc*_*nzo 6

您可以将"日志文件"作为普通文件读取.

然后,您可以使用正则表达式来获取所需的字符串部分:

try{
   FileInputStream fstream = new FileInputStream("abc.log");
   BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
   String strLine;
   /* read log line by line */
   while ((strLine = br.readLine()) != null)   {
     /* parse strLine to obtain what you want */
     System.out.println (strLine);
   }
   fstream.close();
} catch (Exception e) {
     System.err.println("Error: " + e.getMessage());
}
Run Code Online (Sandbox Code Playgroud)

  • 这有用吗?当你刚才给出答案时,人们不会学习,很明显OP没有试过*任何东西* (3认同)
  • 请不要使用DataInputStream来阅读文本http://vanillajava.blogspot.co.uk/2012/08/java-memes-which-refuse-to-die.html (2认同)