分离解析方法

时间:2018-04-02 11:20:59

标签: java parsing file-io

我正在创建一个处理SKU的程序。我目前在我的程序中有两个类,SKU类是主类,Store类初始化ArrayListSKU对象存储在数组中。我目前在SKU类中有一个方法,它从文件中获取输入,解析数据并使用String标记器在对象变量中存储数据,并将对象添加到{{{}中的数组中。 1}}类。我面临的问题是,我想要在Store类中分离解析方法,以便它只是从一行读取,然后有一个单独的方法,它接受一个文件输入解析器并最终更新我的SKU类,以便使用解析的数据初始化产品。拜托,您可以帮我解决这个问题吗?

Store类中的解析方法目前如下:

SKU

我的public void parser() { try { // create a Buffered Reader object instance with a FileReader BufferedReader br = new BufferedReader(new FileReader("products.txt")); // read from first line from the text file String fileRead = br.readLine(); // skip first line from sample file as it contains headings int lineNumber = 0; // loop until all lines are read while (fileRead != null) { if(lineNumber == 0) { lineNumber++; continue; } lineNumber++; // use string.split to load a string array with the values from each line of // the file, using a tab as the delimiter String[] tokenize = fileRead.split("\t"); // assume file is made correctly // and make temporary variables for the three types of data String tempProductCode = tokenize[0]; String tempDescription = tokenize[1]; BigDecimal tempPrice = new BigDecimal(tokenize[2]); // create temporary instance of SKU object // and load with three data values SKU tempObj = new SKU(); tempObj.setProductCode(tempProductCode); tempObj.setDescription(tempDescription); tempObj.setPrice(tempPrice); // add to array list Store.mySkuArrayList.add(tempObj); // read next line before looping // if end of file reached fileRead = br.readLine(); } // close file stream br.close(); } // handle exceptions catch (FileNotFoundException fnfe) { System.out.println("file not found"); } catch (IOException ioe) { ioe.printStackTrace(); } } 课程如下:

Store

2 个答案:

答案 0 :(得分:1)

将代码拆分为三个单独的类。 SkuFile类表示存储sku代码的文本文件,该类知道如何存储并能够解析它的每个sku条目。 Sku类包含数据。商店类包含 Sku列表并在其构造函数中接受SkuFile。

class SkuFile {
    private String path;

    SkuFile(String path) {
        this.path = path;
    }


    List<Sku> readAllSku() {
        ArrayList<Sku> result = new ArrayList<>();
        try {
            List<String> lines = Files.readAllLines(new File(path).toPath());
            for(String skuLine : lines) {
                result.add(parseFrom(skuLine));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    private Sku parseFrom(String data){
        String[] tokenize = data.split("\t");
        productCode = tokenize[0];
        description = tokenize[1];
        price = new BigDecimal(tokenize[2]);
        return new Sku(productCode, description, price);
    }
}

class Sku {
    private String code;
    private String description;
    private BigDecimal price;

    Sku(String code, String description, BigDecimal price) {
        this.code = code;
        this.description = description;
        this.price = price;   
    }

    //getters setters methods
}


class Store {
    private List<Sku> skus;

    Store(SkuFile file) {
        skus = file.readAllSku();
    }
}


class Test {

    public static void main(String[] args) {
        Store store = new Store(new SkuFile("products.txt"));
    }
}

答案 1 :(得分:0)

处理此问题的一种方法是使parse方法返回标记符列表(例如List tokenizeList)和第二种方法,该方法将该列表作为输入并填充 SkuArrayList

解析器方法的可能实现

public List<String[]> parser() {
    List<String[]> tokenizeList = new ArrayList<>();
    try {
        ... /*file opening logic*/
        while (fileRead != null)
        {
            .../*line counting logic*/
            String[] tokenize = fileRead.split("\t");
            tokenizeList.add(tokenize);

            fileRead = br.readLine();
        }

        // close file stream
        br.close();
    }// handle exceptions
    catch (FileNotFoundException fnfe)
    {
        System.out.println("file not found");
    }
    catch (IOException ioe)
    {
        ioe.printStackTrace();
    }
    return tokenizeList;
}

可能实现populate商店方法

public void populateStore(List<String[]> tokenizeList) {
    for(String[] tokenize: tokenizeList) {
         String tempProductCode = tokenize[0];
         String tempDescription = tokenize[1];
         BigDecimal tempPrice = new BigDecimal(tokenize[2]);

         SKU tempObj = new SKU();
         tempObj.setProductCode(tempProductCode);
         tempObj.setDescription(tempDescription);
         tempObj.setPrice(tempPrice);

         // add to array list
         Store.mySkuArrayList.add(tempObj);
    }
}

从你调用这两种方法的主要方法

public void foo() {
    populateStore(parser());
}