Question

I've been searching the web but to no avail.

My problem is that I have one log text file that contains text like

2014-03-04 08:28:45 1WKkiT-0008Qr-M9 Message received from xx (1.2.3.41) T="q"
2014-03-04 08:28:45 1WKkiT-0008Qr-M9 Message was delivered to xxxH=xxx[11.11.11.1] C="250 Queued (0.000 seconds)"
2014-03-04 08:28:45 1WKkiT-0008Qr-M9 Completed

2014-03-04 08:28:45 1WKkiT-0008Qr-M9 DKIM: d=x=relaxed/relaxed a=rsa-sha1 t=1393921721 [verification succeeded]
2014-03-04 08:29:12 1WKkit-0005cD-UZ Message received from x x T="x"
2014-03-04 08:29:12 1WKkit-0005cD-UZ Message was delivered to xxxH=x xxx C="250 Queued (0.000 seconds)"
2014-03-04 08:29:12 1WKkit-0005cD-UZ Completed

The actual file is much larger.

What I would like is to read this whole file block by block (the blank line as a separator) and then write each block to another pre-made text file as I do so.

I am currently using a BufferedReader and BufferedWriter but am not married to the idea of using these.

Any help would be greatly appreciated, thanks

Was it helpful?

Solution

I think this is what you want:

BufferedReader reader = new BufferedReader(new FileReader("text.txt"));
    String line = null;
    ArrayList<String> block = new ArrayList<String>();
    String tmp="";
    while ((line = reader.readLine()) != null) {
        if(line.equals(""))
        {
            block.add(tmp);
            tmp="";
        }
        else
        {
            tmp = tmp + line;
        }
    }
    block.add(tmp);
            reader.close();
    System.out.println(block.size());
    System.out.println(block.toString());

Just run a for loop to copy that to another text file.

Replace

tmp = tmp + line";

with

tmp = tmp + line+"\n";

if you want your string in the same format with the source file

OTHER TIPS

Here's a solution using a StringBuilder and a simple loop. Feel free to adjust it for your own needs!

public List<String> extractBlocks(File file) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(file));

    String line;
    StringBuilder block = new StringBuilder();
    List<String> blocks = new ArrayList<String>();
    while ((line = reader.readLine()) != null) {
        if (line.isEmpty()) {
            blocks.add(block.toString());
            block = new StringBuilder();
        } else {
            block.append(line);
        }
    }
    blocks.add(block.toString());

    reader.close();

    return blocks;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top