来自java中文本文件的两个单词之间的块数据

时间:2017-09-13 16:35:37

标签: java design-patterns chunks

我有一个.txt文件,其中数据采用以下格式。

Start-enclosure
Standard
African Safari Enclosure
09am
05pm
Ram
Safari Enclosure for animals requiring large roaming area
30
Start-animl
Elephant
400

Giraffe
350

Lion
300
End-enclosure


Start-enclosure
Premium
Standard Australian Enclosure
09am
09pm
Shyam
Standard Enclosure for animals available in australia
30
5
Start-animl
Koala
8

Wormbat
25

Wallaby
20
End-enclosure

我想将这些数据存储在List<Enclosure>类似于使用开关案例(标准版,高级版)并以此格式存储数据

Enclosure Name
Opening Time
Closing Time
Enclosure Manager
Description
Entry Price

List<Animals> { animal name, animal weight }

我怎样才能实现它。我希望在 Start-enclosure End-enclosure 之间以某种方式 chunk 数据并从数据循环。但是我如何实现它我正在尝试它,但我需要一个方向走直路。

3 个答案:

答案 0 :(得分:0)

我在下面编写代码,用于根据开始和结束分块数据,并且它对我来说很好。

您可以使用附件

修改开始和结束
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class ChunkTest{

    static List<String> sList = new ArrayList<>();

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub

        sList = new Tester().test();
        sList.forEach((d) -> System.out.println(d));

    }

    private List<String> test() throws IOException {

        String str = "", str2 = "";
        FileInputStream fileInputStream = new FileInputStream(new File("path/to/text/file"));
        BufferedReader br = new BufferedReader(new InputStreamReader(fileInputStream));
        while ((str = br.readLine()) != null) {
            if (!str.equals("start")) {
                str2 = str2 + "\n" + str;
            }
            if (str.equals("end")) {
                sList.add(str2.replace("end", ""));
                str2 = "";
            }

        }

        return sList;
    }

}

使用以下数据进行测试:

start
1
2
3
4
end

start
5
6
7
8
end

答案 1 :(得分:0)

您的输入文件的第二个附件有两行价格,即 30 5 。那是一个错字吗? (因为您建议的变量&#39; 条目价格&#39; 列表)...并且您的算法将根据答案而有所不同。

答案 2 :(得分:0)

您可以通过一个循环实现所需的实现。但是,您必须遵守有关输入文本文件的一些要求:

  • 可以忽略机箱之间的空行
  • 动物部分内的空白行可以忽略
  • 机箱相关字段显示在Start-animl部分
  • 之前
  • 围栏&amp;动物领域以确定的顺序出现

根据上述要求,您可以实现目标,如代码所示。正如您所看到的,实施确实需要相当多的簿记。你应该研究代码并理解它。还要了解代码中上述要求的含义。例如,如果字段顺序发生变化,代码将无法运行,除非您进行相应的代码更改。

public class FileParser {

    static class Animal {
        String name;
        String weight;

        @Override
        public String toString() {
            return "(" + name + "," + weight + ")";
        }
    }

    static class Enclosure {

        String EnclosureName;
        String EnclosureType;
        String OpeningTime;
        String ClosingTime;
        String EnclosureManager;
        String Description;
        String EntryPrice;
        String PriceModifier;
        List<Animal> Animals;

        @Override
        public String toString() {
            return
                    "\tEnclosureName [" + EnclosureName + "]\n" +
                    "\tOpeningTime [" + OpeningTime + "]\n" +
                    "\tClosingTime [" + ClosingTime + "]\n" +
                    "\tEnclosureManager [" + EnclosureManager + "]\n" +
                    "\tDescription [" + Description + "]\n" +
                    "\tEntryPrice [" + EntryPrice + "]\n" +
                    "\tPriceModifier [" + PriceModifier + "]\n" +
                    "\tAnimals " + Animals
                    ;
        }
    }

    private static Map<String,ArrayList<Enclosure>> parse(File inputFile)
            throws IOException {

        Map<String,ArrayList<Enclosure>> enclosureMap = new HashMap<>();
        final int SECTION_NOOP = 0, SECTION_ENCLOSURE = 1, SECTION_ANIMAL = 2;
        int sectionType = SECTION_NOOP;

        try ( BufferedReader br = new BufferedReader(new FileReader(inputFile)) ) {
            String line;
            int enclosureLineNumber = 0, animalLineNumber = 0;
            String encType = "";
            Enclosure enclosure = null;
            while ( (line = br.readLine()) != null ) {

                String text = line.trim();

                // ignore blank lines
                if ( text.length() == 0 && (sectionType == SECTION_NOOP || sectionType == SECTION_ANIMAL) ) {
                    continue;
                }

                switch (text) {
                    case "Start-enclosure":
                        sectionType = SECTION_ENCLOSURE;
                        enclosure = new Enclosure();
                        enclosure.Animals = new ArrayList<>();
                        enclosureLineNumber++;
                        break;
                    case "Start-animl":
                        sectionType = SECTION_ANIMAL;
                        animalLineNumber++;
                        break;
                    case "End-enclosure":
                        sectionType = SECTION_NOOP;
                        enclosureLineNumber = 0;
                        animalLineNumber = 0;
                        if ( enclosure != null ) {
                            enclosureMap.get(encType).add(enclosure);
                        }
                        enclosure = null;
                        break;
                    default:
                        if ( enclosure != null && sectionType == SECTION_ANIMAL ) {
                            // line is from inside the Animals section
                            Animal theAnimal;
                            switch ( animalLineNumber )  {
                                case 1:
                                    theAnimal = new Animal();
                                    theAnimal.name = text;
                                    enclosure.Animals.add(theAnimal);
                                    animalLineNumber = 2;
                                    break;
                                case 2:
                                    theAnimal = enclosure.Animals.get( enclosure.Animals.size() -1 );
                                    theAnimal.weight = text;
                                    animalLineNumber = 1;
                                    break;
                                default:
                                    break;
                            }
                        } else if ( enclosure != null && sectionType == SECTION_ENCLOSURE ) {
                            // line is from the Enclosure (before Animals)
                            switch (enclosureLineNumber) {
                                case 1:
                                    encType = text;
                                    enclosure.EnclosureType = text;
                                    if ( !enclosureMap.containsKey(encType) ) {
                                        enclosureMap.put( encType, new ArrayList<>() );
                                    }
                                    break;
                                case 2:
                                    enclosure.EnclosureName = text;
                                    break;
                                case 3:
                                    enclosure.OpeningTime = text;
                                    break;
                                case 4:
                                    enclosure.ClosingTime = text;
                                    break;
                                case 5:
                                    enclosure.EnclosureManager = text;
                                    break;
                                case 6:
                                    enclosure.Description = text;
                                    break;
                                case 7:
                                    enclosure.EntryPrice = text;
                                    break;
                                case 8:
                                    enclosure.PriceModifier = text;
                                    break;
                                default:
                                    break;
                            }
                            enclosureLineNumber++;
                        } else {
                            // ignore lines that are not part of Enclosure
                        }
                        break;
                }

            }
        }

        return enclosureMap;
    }

    public static void main(String[] args) throws IOException {
        if ( args.length != 1 ) {
            System.err.println("Missing filename argument");
            System.exit(1);
        }
        File inputFile = new File(args[0]);
        if ( !inputFile.canRead() ) {
            System.err.println(args[0] + ": does not exist or unreadable");
        }

        Map<String,ArrayList<Enclosure>> enclosureMap = parse(inputFile);

        enclosureMap.entrySet().forEach((entry) -> {
            System.out.println("Enclosures of Type = " + entry.getKey() + "\n");
            entry.getValue().forEach((enclosure) -> {
                System.out.println(enclosure + "\n");
            });
        });
    }

}

对于您的输入文件,上述代码生成的输出为:

Enclosures of Type = Standard

    EnclosureName [African Safari Enclosure]
    OpeningTime [09am]
    ClosingTime [05pm]
    EnclosureManager [Ram]
    Description [Safari Enclosure for animals requiring large roaming area]
    EntryPrice [30]
    PriceModifier [null]
    Animals [(Elephant,400), (Giraffe,350), (Lion,300)]

Enclosures of Type = Premium

    EnclosureName [Standard Australian Enclosure]
    OpeningTime [09am]
    ClosingTime [09pm]
    EnclosureManager [Shyam]
    Description [Standard Enclosure for animals available in australia]
    EntryPrice [30]
    PriceModifier [5]
    Animals [(Koala,8), (Wormbat,25), (Wallaby,20)]