如何在Java

时间:2018-05-28 08:48:17

标签: java split

对于学校项目,我需要从文本文件中提取消息。我创建了一个消息类:

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;
    }
}

文本文件如下所示:

From: sender
To: Address
blah blah blah
blah blah(can be more then one line)
#(represent end of message)
From: sender2
To: Address2
blah blah blah
blah blah(can be more then one line)
#

我需要从该文本文件创建消息的ArrayList,但我不确定如何拆分它。为了澄清,发件人,收件人和正文用新行分隔,消息以“#”结尾。

2 个答案:

答案 0 :(得分:3)

我写了parse(),这是Message类的解析方法。我还在main()中编写了一个简单的测试来演示如何将文本文件拆分为单独的消息。请注意,此解决方案有局限性。它将整个文本文件作为String保存在内存中。如果文本文件是一个或多个GB大,则必须找到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);
    }
}

答案 1 :(得分:1)

您可以修改Message课程:

class Message {

    private String from = "";
    private String to = "";
    private String body = "";

    public void setFrom(String from) {
        this.from = from;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public void addBody(String body) {
        if (!this.body.isEmpty())
            this.body += '\n';
        this.body += body;
    }
}

然后只需从文本文件中读取所有行,然后逐行创建Message实例:

private static List<Message> getMessages(List<String> lines) {
    final String separator = "#";
    final String from = "From:";
    final String to = "To:";

    Message message = null;
    List<Message> messages = new ArrayList<>();

    for (String line : lines) {
        if (line.startsWith(separator))
            message = null;
        else {
            if (message == null)
                messages.add(message = new Message());

            if (line.startsWith(from))
                message.setFrom(line.substring(from.length()).trim());
            else if (line.startsWith(to))
                message.setTo(line.substring(to.length()).trim());
            else
                message.addBody(line);
        }
    }

    return messages;
}

P.S。 要将文本文件作为ines列表阅读,请使用例如List<String> lines = Files.readAllLines(Paths.get("data.txt"));