Java 将数据从.txt文件返回到arraylist

Java 将数据从.txt文件返回到arraylist,java,Java,好的,我得到了一个包含两个对象的txt文件,它们拥有构造函数要求的描述、成本和折旧百分比。在我的tostring方法中,我只要求返回我输入的一些值。我省略了所有用来计算当前值的方法,因为它们与我要问的问题无关 public class InventoryItem { private String description; private double cost, percentDepreciated; public static final double DEPRECI

好的,我得到了一个包含两个对象的txt文件,它们拥有构造函数要求的描述、成本和折旧百分比。在我的tostring方法中,我只要求返回我输入的一些值。我省略了所有用来计算当前值的方法,因为它们与我要问的问题无关

public class InventoryItem {

    private String description;
    private double cost, percentDepreciated;
    public static final double DEPRECIATION_MIN = 0.0,
            DEPRECIATION_MAX = 1.0;

    public InventoryItem(String descriptionIn, double costIn, double percentDepreciatedIn) {
        description = descriptionIn.trim();
        cost = costIn;
        percentDepreciated = percentDepreciatedIn;
    }
    public String toString() {
        DecimalFormat df = new DecimalFormat("#,###.00");
        String output;
        output = "Description: " + description;
        output += "\nCost: $" + df.format(cost);
        output += "\tPercent Depreciation: " + (percentDepreciated * 100 + "%");
        output += "\nCurrent Value: $" + df.format(currentValue());
        if (isEligibleToScrape()) {
            output += "\n*** Eligible to scape ***";
        }
        if (percentDepreciatedOutOfRange()) {
            output += "\n*** Percent Depreciated appears to be out of range ***";
        }
        return output;
    }
}
所以我要问的是,现在我得到了一个包含多个对象的上述信息的txt文件,我如何返回每个InventoryItem对象的信息,并将其格式化为上述toString方法。我需要在我的Inventory类的下面的toString方法中执行此操作

public class Inventory {

    private String name;
    private ArrayList<InventoryItem> inventoryList = new ArrayList<InventoryItem>();

    public Inventory(String nameIn, ArrayList<InventoryItem> inventoryListIn) {
        name = nameIn;
        inventoryList = inventoryListIn;
    }
    public String toString() {
    }
}

我想说toString方法有完全不同的用途,用这种方式实现它是一个非常糟糕的主意。您需要的是针对InventoryItem类的某种“文本序列化程序”


至于问题本身,如果你真的绝对需要这样做。。。您只需创建一个StringBuilder并将每个InventoryItem的toString方法的输出附加到它。

如果我理解正确,您需要从.txt文件获取数据并在程序中使用该数据。要从.txt文件获取数据,可以使用Scanner类,如本例所示:

Scanner s = new Scanner(new BufferedReader(new FileReader("your-txt-file.txt")));
然后,要扫描每一行,您应该使用:

while (s.hasNext()) {
    // Here you should decompose every line of string to the desired variables
}

您可以使用.substring删除字符串的一部分,并将这些值分配给变量。

您的.txt文件是否包含整个toString方法?@borisverward它包含库存名称,后跟说明、成本和折旧百分比。这样:二手车库存2012吉普32000.35 1990丰田18000.95 2013本田26000-.20 2013福特22000 1.20在这些评论中,每个值都返回到一个新行中。在这些评论中,我不会这样做。如果toString的唯一目的是提供信息性文本,您可以简单地使用name++inventoryList。这将调用ArrayList的toString方法,该方法将依次包含其每个元素的字符串形式。