复杂的.txt文件解析Android Studio

问题描述 投票:0回答:1

我需要解析表单中的文本文件:

Encanto, 6/101-105, 7/320-322
Flora, 1/2-5
Vista, 7/67-70
WORK ORDER

我知道如何使用以下方法将具有“name,number”形式的行的.text文件解析为两个单独的ArrayLists:

BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String line;
while( (line = bufferedReader.readLine()) != null){
allNames.add(line.split(", ")[0]);
allNums.add(Integer.parseInt(line.split(",\\s+")[1]));
}
bufferedReader.close();

现在我必须让列表包含这些项目:

ArrayList<String> names = {"Encanto", "Flora", "Vista", "WORK ORDER"};

ArrayList<String> lots = {"Bld.6 101", "Bld.6 102", "Bld.6 103", "Bld.6 104", "Bld.6 105", "Bld.7 320", "Bld.7 321", "Bld.7 322"};
ArrayList<String> lots1 = {"Bld.1 2", "Bld.1 3", "Bld.1 4", "Bld.1 5",};
ArrayList<String> lots2 = {"Bld.7 67", "Bld.7 68", "Bld.7 69", "Bld.7 70"};
java android
1个回答
0
投票

创建此Parser类

class Parser {
    String parseName(String line) {
        String[] blocks = line.split(", ");
        if (blocks.length > 0) {
            return blocks[0];
        }
        return null;
    }

    List<String> getLots(String line) {
        List<String> lotList = new ArrayList<>();
        String[] blocks = line.split(", ");
        for (String block : blocks) {
            // I suppose that lot line will always have "/" and "-"
            if (block.contains("/") && block.contains("-")) {
                lotList.addAll(generateLots(block));
            }
        }
        return lotList;
    }

    private List<String> generateLots(String block) {
        List<String> lots = new ArrayList<>();
        String prefix = "Bld.";
        String bldNumber = block.substring(0, block.indexOf("/"));
        int lowest = Integer.parseInt(block.substring(block.indexOf("/") + 1, block.indexOf("-")));
        int highest = Integer.parseInt(block.substring(block.indexOf("-") + 1, block.length()));
        for (int i = lowest; i <= highest; i++) {
            lots.add(prefix + bldNumber + " " + i);
        }
        return lots;
    }
}

然后在您的代码中使用它

// create a new Parser object
Parser parser = new Parser();
// get name
System.out.println(parser.parseName(line));
// get lots
List<String> lotList = parser.getLots(line);
for (String lot : lotList) {
    System.out.println(lot);
}

=========================================================

编辑:要回答您的评论,您可以动态创建批次列表。如果我提到你的问题,就会这样

BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String line;
Parser parser = new Parser();
List<String> names = new ArrayList<>();
List<List<String>> lotsList = new ArrayList<>();
while ((line = bufferedReader.readLine()) != null) {
    names.add(parser.parseName(line));
    lotsList.add(parser.getLots(line));
}
bufferedReader.close();
© www.soinside.com 2019 - 2024. All rights reserved.