I wrote parse()
, a parsing method for your Message class. I also wrote a simple test in main()
to demonstrate how to split the text file into separate messages. Please note that this solution has limitations. It keeps the whole text file in memory as String. Should the text file be one or more GB large, there has to be found a Stream processing solution along the lines of this question.
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
public class Message {
private String from;
private String to;
private String body;
public Message(String from, String to, String body) {
this.from = from;
this.to = to;
this.body = body;
}
public String toString() {
return "From: " + from + "\n" +
"To: " + to + "\n" +
"Body: " + body;
}
// creates a messsage object from a string
public static Message parse(String msg) {
if (msg == null || StringUtils.countMatches(msg, "\n") <= 2) {
throw new IllegalArgumentException("Invalid string! Needing a string with at least 3 lines!");
}
// first, find from and to with two splits by new line
String[] splits = msg.split("\n");
// replace the non-informative 'From: " beginning, should it be there
String from = splits[0].replace("From: ", "");
// replace the non-informative 'To: " beginning, should it be there
String to = splits[1].replace("To: ", "");
// the rest is body
String body = msg.substring(msg.indexOf(to) + to.length() + 1, msg.length());
// remove leading and trailing whitespaces
body = StringUtils.trim(body);
return new Message(from, to, body);
}
public static void main(String[] args) {
List<Message> allMessages = new ArrayList<>();
String text = "From: sender\n" +
"To: Address\n" +
"blah blah blah\n" +
"blah blah(can be more then one line)\n" +
"#\n" +
"From: sender2\n" +
"To: Address2\n" +
"blah blah blah\n" +
"blah blah(can be more then one line)";
// split the text by what separates messages from each other
String[] split = text.split("#\n");
for (String msg : split) {
allMessages.add(Message.parse(msg));
}
// print each message to System.out as a simple means of demonstrating the code
allMessages.forEach(System.out::println);
}
}