簡體   English   中英

從Java文本文件中的兩個單詞之間分塊數據

[英]Chunk data between two words from a text file in java

我有一個.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 }

我該如何實現。 我希望有一些方法可以在開始外殼結束外殼之間分數據,並從數據循環。 但是我要如何實現它,但是我需要一個方向。

我在下面編寫了用於基於開始和結束對數據進行分塊的代碼,它對我來說很好用。

您可以修改機箱的開頭和結尾

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

輸入文件的第二個附件包含兩行價格,即305 那是錯字嗎? (因為您建議的變量“ Entry Price不在列表中)...而且您的算法將根據答案而有所不同。

您可以通過一個循環來實現所需的實現。 但是,您必須遵守有關輸入文本文件的一些要求:

  • 機箱之間的空白行可以忽略
  • 動物部分內的空白行可以忽略
  • 與機箱相關的字段出現在“開始animl”部分之前
  • 圍欄和動物場以確定的順序出現

通過上述要求,您可以實現目標,如代碼所示。 如您所見,該實現確實需要一定的簿記。 您應該學習代碼並理解它。 還應了解代碼中上述要求的含義。 例如,除非您進行了相應的代碼更改,否則如果字段順序更改,代碼將無法工作。

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)]

暫無
暫無

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

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