简体   繁体   English

如何从文件中提取数据并创建对象表 java?

[英]How to extract data from a file and create a table of objects java?

Hey i was wondering how can i create a table of objects in java using a text file I've created my table嘿,我想知道如何使用我创建表格的文本文件在 java 中创建对象表格

Table tab[] = new Table[6]

and here's my text file:这是我的文本文件:

id|des|pr

50 | Internet Fibre 50                          | 40.00

150| Internet Fibre 150                         | 50.00

500| Internet Fibre 500                         | 90.00

B  | Forfait Bien                               | 60.00

T  | Forfait Très Bien                          | 40.00

E  | Forfait Excellent                          | 30.00

I've created my table我已经创建了我的表

Table tab[] = new Table[6]

I'd like to read each line (except the first line ) and make it an object (the type is Table) in the table above (tab) by sperating the "|"我想阅读每一行(第一行除外)并通过分隔“|”使其成为上表(选项卡)中的 object(类型为表) on each line so i'll have 6 objects in total each one will follow this constructor在每一行,所以我总共有 6 个对象,每个对象都遵循这个构造函数

Table newTable = new Table(id , des , pr); 

Thanx !谢谢!

Try the below code:试试下面的代码:

Main.java主要.java

    Table[] tabs = new Table[6];
    BufferedReader bufferedReader = new BufferedReader(new FileReader("File location")); // add your file location here
    bufferedReader.readLine(); // ignoring the header line
    String row = bufferedReader.readLine();
    int count = 0;
    while (row != null) {
        String[] split = row.split("\\|");
        tabs[count]  = new Table(split[0].trim().replace("\\t", ""), split[1].trim().replace("\\t", ""), Double.parseDouble(split[2].trim().replace("\\t", "")));
        count++;
        row = bufferedReader.readLine();
    }

Table.java表.java

public class Table {
    private String id;
    private String des;
    private double price;

    public Table(String id, String des, double price) {
        this.id = id;
        this.des = des;
        this.price = price;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getDes() {
        return des;
    }

    public void setDes(String des) {
        this.des = des;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Table{" +
                "id='" + id + '\'' +
                ", des='" + des + '\'' +
                ", price=" + price +
                '}';
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM