Read Text Data by a Mark to Write to Multiple Files

Question

I am working with a TXT file. My expectation: Each time string “flag” appears the program returns the retrieved data and writes it to a target TXT file; and then goes on to read until the next “flag” appears; and so on. I use Split to read data only to get a wrong format.

Below is the sample data:

line-------1

line-------2

line-------3

line-------4

flagline-------5

line-------1

line-------2

line-------3

line-------4

line-------5

line-------6

line-------7

line-------8

line-------9

flagline-------10

line-------1

line-------2

line-------3

line-------4

line-------5

line-------6

line-------7

line-------8

line-------9

line-------10

line-------11

line-------12

line-------13

line-------14

flagline-------15

 

Is there any idea? Thanks in advance.

 

Answer

It’s inconvenient to do this in Java. We can handle it in SPL (Structured Process Language). The script has 3 lines only:

A

1

=file("E:\\s.txt").read()

2

=A1.split("flag")

3

>A2.(file("E:\\result"+string(#)+".txt").write(~))

A1: Read the text file as a string;

A2: Split the string into multiple segments by “flag”;

A3: Write each segment to a txt file.

An SPL script can be easily embedded into a Java application, see How to Call an SPL Script in Java to learn details.