复杂的.txt文件解析Android Studio

时间:2019-04-13 15:42:48

标签: java android

我需要解析以下形式的文本文件:

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

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

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

1 个答案:

答案 0 :(得分:0)

创建此解析器类

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