Java String拆分多个对象

时间:2018-01-08 22:09:53

标签: java string split

我正在尝试创建一个库存控制Java项目,该项目可以读取多个"产品"从文本文件中创建"产品"在运行时包含数据的对象。我文本文件中当前数据格式的一个示例是:

4462:Coca-Cola 2L Bottle:1.69;4980:Andrex 4 Pack:1.99;2620:Haribo Strawbs 80g:0.50;3223:Pedigree in gravy (with Chicken):0.75;

我使用:分隔特定产品的不同变量,并使用;分隔不同的产品。

我如何提取产品变量并将其与不同产品区分开来?

1 个答案:

答案 0 :(得分:0)

你走在正确的轨道上。重要的是分两次 - 一次是产品,一次是个别属性。

首先,创建一个定义每个产品的类。我猜测了这个例子中字段的含义:

class Product {
    String id;
    String name;
    String price;
}

现在,您可以从文件中读取文件并构建产品实例。

// Read the entire file
String text = new String(Files.readAllBytes(Paths.get("D:/input.txt")), StandardCharsets.UTF_8);

// Split into an array of strings, representing products
String[] prodStr = text.split(";");

// Create a list of product objects, currently empty
List<Product> prodList = new ArrayList<>();

// Loop over each product string
for (String pr : prodStr) {

    // Split this string into separate fields
    String[] fields = pr.split(":");

    // Build a product object from the fields
    Product product = new Product();
    product.id = fields[0];
    product.name = fields[1];
    product.price = fields[2];

    // Add this product to the list
    prodList.add(product);

}

// Print all the products to see what we get
System.out.println(prodList);

我在Product类中添加了toString()方法,并使用您的示例数据运行此代码:

[Product{id='4462', name='Coca-Cola 2L Bottle', price='1.69'}, Product{id='4980', name='Andrex 4 Pack', price='1.99'}, Product{id='2620', name='Haribo Strawbs 80g', price='0.50'}, Product{id='3223', name='Pedigree in gravy (with Chicken)', price='0.75'}]

要区分产品,请实施hashCode()equals()。例如一个非常简单的解决方案可能是:

@Override
public int hashCode() {
    return id.hashCode();
}

@Override
public boolean equals(Object o) {
    Product product = (Product) o;
    return id.equals(product.id);
}