簡體   English   中英

如何在Java中拆分和解析文本文件

[英]How to split and parse a text file in Java

對於學校項目,我需要從文本文件中提取消息。 我創建了一個消息類:

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,但是我不確定如何拆分它。 只是為了澄清起見,發件人,收件人和正文用換行分隔,消息以“#”結尾。

我寫了parse() ,它是Message類的解析方法。 我還在main()編寫了一個簡單的測試,以演示如何將文本文件拆分為單獨的消息。 請注意,此解決方案有局限性。 它將整個文本文件保留為String。 如果文本文件的大小為一個或多個GB,則必須按照此問題找到流處理解決方案。

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

您可以修改您的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;
}

PS要讀取文本文件作為ines列表,請使用例如List<String> lines = Files.readAllLines(Paths.get("data.txt"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM