将文本文件解析为模型对象

时间:2017-12-03 13:49:07

标签: java input file-io

我正在尝试从文件中读取文字。使解析器计算STP  试图将文本解析为模型:

`this is a text.txt`
[BRIDGE 1]
BridgeId = 42
[BRIDGE 1.Port 01]
PathCost = 10
ConnectedTo = LAN A
[BRIDGE 1.Port 02]
PathCost = 10
ConnectedTo = LAN B

[BRIDGE 2]
BridgeId = 97
[BRIDGE 2.Port 01]
PathCost = 05
ConnectedTo = LAN C
[BRIDGE 2. Port 02]
PathCost = 10
ConnectedTo = LAN A
[BRIDGE 2. Port 03]
PathCost = 05
ConnectedTo = LAN D

# Header 1 #

КлассBridge - этороутерисоответственноPortalэтопортыроутера 模型类:

Bridge.java:

public class Bridge {
    private int id;
    private int priority;
    private List<Port> ports = Collections.emptyList();

    public Bridge(int id, int priority, List<Port> ports) {
        this.id = id;
        this.priority = priority;
        this.ports = ports;
    }

    public int getId() {
        return id;
    }

    public int getPriority() {
        return priority;
    }

    public List<Port> getPorts() {
        return ports;
    }
}

Port.java:

public class Port {
    private int portId;
    private int pathCost;
    private String connectedTo;

    public Port(int portId, int pathCost, String connectedTo) {
        this.portId = portId;
        this.pathCost = pathCost;
        this.connectedTo = connectedTo;
    }

    public int getPortId() {
        return portId;
    }

    public int getPathCost() {
        return pathCost;
    }

    public String getConnectedTo() {
        return connectedTo;
    }
}

用法:

public List<Bridge> parseFile(String fileName) {
    File file = new File(fileName);
    List<Bridge> bridges = Collections.emptyList();
    try (Scanner scanner = new Scanner(file)) {
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            int bId = scanner.
            if (line.startsWith("[") && !line.contains(".")){
                bridges.add(new Bridge(line.next))
            };
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return ;
}

所以我被困在这里,无法弄清楚如何组织解析。 首先阅读哪个对象?创建端口然后读取行 并通过端口列表填充Bridge

0 个答案:

没有答案