How to Write Txt Data Conditionally into a CSV file

Question

I want to read a text file in Java. The file is log.txt containing data in the Eclipse console.
——————————————————————————————————————
Here’s my data:
[2013-08-26 10:45:45,042] ERROR does not exist.
[2013-08-26 14:43:09,145] ERROR Certification failed.
[2013-08-26 14:43:09,145] ERROR Certification failed.
[2013-08-26 14:43:10,973] ERROR Certification failed.
[2013-08-26 14:43:33,285] ERROR Certification failed.
[2013-08-28 09:23:12,920] INFO Login succeeded.User ID=[CSDN123]
[2013-09-02 10:13:32,793] INFO Login succeeded.User ID=[CSDN123]
[2013-09-02 10:36:05,050] INFO Login succeeded.User ID=[CSDN123]
[2013-09-02 10:48:26,407] INFO Login succeeded.User ID=[CSDN123]
——————————————————————————————————————
From left to right: [Time] [Level (Error, Info, Warning, etc.)] [Content]

My problem: 1. Write the above error reports during a certain time period (like from 2013-08-26 to 2013-09-01) into a csv file in the structure of Time, Level (Error, Info, Warning, etc.), Content; Or 2. Write the error reports of a certain level (ERROR, for instance) into a csv file of the same structure.

 

Answer

It’s really complicated to do this automatically in Java because the language lacks relative class libraries. It’s convenient to handle it in SPL. The SPL language can parse the log data into a two-dimensional table sequence and write it into a csv file. Here’s the SPL script:

A

1

=file("E:\\log.txt").import@i()

2

=A1.(~.split("")).new(~(1):time,~(2):level,~.to(3,).concat("   "):content)

3

=A2.select(mid(time,2,23)>="2013-08-26"    &&   mid(time,2,23)<="2013-09-01")

4

=file("E:\\result.csv").export@tc(A3)

A1: Import data from the text file log.txt as a sequence by making each line a member;

undefined

A2: Split each member of A1’s sequence into 3 parts and create a new table sequence made up of time, level and content fields:

undefined

A3: Perform a filtering to select records from 2013-08-26 to 2013-09-01;

undefined

A4: Write A3 to a csv file.

It’s easy to embed an SPL script into a Java application. For details, see How to Call an SPL Script in Java