Java 从文件读入arraylist,然后将数组列表划分为多个字符串,这样我就可以单独解析它们

Java 从文件读入arraylist,然后将数组列表划分为多个字符串,这样我就可以单独解析它们,java,string,file,parsing,arraylist,Java,String,File,Parsing,Arraylist,因此,在我的部分作业中,我必须从Java之外的文件中提取信息。我已经完成了那部分。问题是,我不确定如何将文件中的字符串实际放入变量或循环中,以便下一部分使用。在下面的代码中,我需要替换代码中显示Item=Tomato的部分。。。从输出文件中使用单数行。我不知道该怎么做。我主要关心的是确保每一行没有硬编码,我猜这将涉及以某种方式或形式在每一行中循环。任何帮助都会很好 我最初是如何以硬编码方式添加项目的,而不是从输出文件输入项目: list.add(new Item("Ketchup", 1

因此,在我的部分作业中,我必须从Java之外的文件中提取信息。我已经完成了那部分。问题是,我不确定如何将文件中的字符串实际放入变量或循环中,以便下一部分使用。在下面的代码中,我需要替换代码中显示Item=Tomato的部分。。。从输出文件中使用单数行。我不知道该怎么做。我主要关心的是确保每一行没有硬编码,我猜这将涉及以某种方式或形式在每一行中循环。任何帮助都会很好

我最初是如何以硬编码方式添加项目的,而不是从输出文件输入项目:

    list.add(new Item("Ketchup", 1.00, 10, 2.00, itemType.FOOD));
    list.add(new Item("Mayo", 2.00, 20, 3.0, itemType.FOOD));
    list.add(new Item("Bleach", 3.00, 30, 4.00, itemType.CLEANING));
    list.add(new Item("Lysol", 4.00, 40, 5.00, itemType.CLEANING));
代码


尝试删除
String item=“番茄,30,1.25,6.50”并用
inventoryList.get(您希望从中获取活动项的位置)替换之后的所有“项”

你需要有一个清晰的策略

您的输入由行组成,而行又由字段组成。您(大概)的目标是将数据作为“记录”进行处理。您可以通过以下两种方式实现:

  • 使用扫描仪读取行,并将每行拆分/扫描/标记为记录字段
  • 将整个输入流作为令牌或值序列进行扫描,并动态重新组合记录
  • 任何一种方法都会奏效。但是你需要决定你要采取哪种方法。。。坚持这一方针

    (如果您刚开始编写或复制代码时没有明确的策略,那么很可能会导致混乱,或者代码不理解,或者两者兼而有之。)

    实现
    publicstaticvoidmain(字符串[]args)引发IOException{
    Path Path=Path.getPath(“inventory.out”);
    列表项=读取项(路径);
    用于(项目:项目){
    System.out.printf(“项目(名称='%s',容量=%d,成本=%f,价格=%f)\n”,
    item.getName()、item.getCapacity()、item.getCost()、item.getPrice());
    }
    }
    公共类项目{
    私有最终字符串名;
    私人最终整数数量;
    私人最终双重成本;
    私人最终双倍价格;
    公共项目(字符串名称、整数容量、双倍成本、双倍价格){
    this.name=名称;
    这个。容量=容量;
    成本=成本;
    这个价格=价格;
    }
    //省略了Getters。
    }
    公共类itemultils{
    /**
    *读取文件中的所有行并将它们映射到项目。
    *
    *@param path文件的路径,非空
    *@返回从文件中读取的项目列表
    *@在读取文件时发生I/O错误或读取格式错误或不可映射的字节序列时引发IOException
    *@如果一行无法映射到项目,则抛出CustomRuntimeException
    */
    公共静态列表readItems(路径路径)引发IOException{
    对象。requirennull(路径);
    返回文件.readAllLines(路径,StandardCharsets.UTF_8)
    .stream()
    .map(ItemUtils::mapStringToItem)
    .collect(Collectors.toList());
    }
    /**
    *将字符串映射到项目。
    *
    *@param str要映射的字符串,非空
    *@返回映射项
    *@如果字符串无法映射到项目,则会引发CustomRuntimeException
    */
    私有静态项mapStringToItem(字符串str){
    字符串[]标记=str.split(“,”);
    if(tokens.length!=4){
    String msg=String.format(“无效项:需要4个令牌,找到%d个令牌”,令牌.length);
    抛出新的CustomRuntimeException(msg);
    }
    试一试{
    字符串名称=令牌[0];
    int quantity=Integer.parseInt(标记[1]);
    double cost=double.parseDouble(令牌[2]);
    double price=double.parseDouble(令牌[3]);
    返回新项目(名称、数量、成本、价格);
    }捕获(数字格式){
    抛出新的CustomRuntimeException(“无效项:类型转换失败”,e);
    }
    }
    private ItemUtils(){
    //实用程序类,防止实例化。
    }
    }
    /**
    *自定义运行时异常。应重命名为更具体的名称。
    */
    公共类CustomRuntimeException扩展了RuntimeException{
    公共CustomRuntimeException(字符串消息){
    超级(味精);
    }
    公共CustomRuntimeException(字符串msg,Throwable e){
    超级(味精,e);
    }
    
    解释
    readLines
    方法用于将所有行读取到字符串列表中,其中每个字符串对应一行。然后我使用Java 8流API处理此列表中的字符串,list类提供了一个返回
    流的方法:

    如果要对的集合对象执行某些操作 示例:筛选、排序或操作该表上的每个元素 对象的基础上,可以使用Java8流特性 用更少的代码轻松完成您的需求

    您可以找到关于流的更实用的解释

    流的方法将
    mapStringToItem
    的方法引用作为其参数。当您查看
    mapStringToItem
    的签名时,您会看到它将单个字符串作为参数并返回一个
    对象。因此,您可以根据需要读取
    .map(…)
    调用“使用方法
    mapStringToItem
    ”将文件中的每一行映射到一个项目。然后我从流中收集所有项目,并使用该方法将它们放入一个新列表中

    让我们看一看
    mapStringToItem
    方法,它使用您分割项目值的方法:首先我们在每个
    处分割行,
    返回一个字符串数组。当前项目类由4个属性组成,应该读取:名称、容量、成本和价格。因此我们检查如果字符串数组
        Scanner s = new Scanner(new File("inventory.out"));
    
        ArrayList<String> inventoryList = new ArrayList<String>();
    
        while (s.hasNext()){
            inventoryList.add(s.next());
        }
        s.close();
    
        System.out.println(inventoryList);
    
        String item = "Tomato,30,1.25,6.50";// input String like the one you would read from a file
    
        String delims = "[,]"; //delimiter - a comma is used to separate your tokens (name, qty,cost, price)
    
        String[] tokens = item.split(delims); // split it into tokens and place in a 2D array.
    
        for (int i=0; i < 4; i++) {
            System.out.println(tokens[i]); // print the tokens.
        }
    
        String name = tokens[0]; System.out.println(name);
    
        int qty = Integer.parseInt(tokens[1]);System.out.println(qty);
    
        double cost = Double.parseDouble(tokens[2]);System.out.println(cost); 
    
    Ketchup,1.00,10,2.00,itemType.FOOD
    Mayo,2.00,20,3.00,itemType.FOOD
    Bleach,3.00,30,4.00,itemType.CLEANING
    Lysol,4.00,40,5.00,itemType.CLEANING
    
    public static void main(String[] args) throws IOException {
        Path path = Paths.getPath("inventory.out");
        List<Item> items = readItems(path);
        for (Item item : items) {
            System.out.printf("Item (name='%s', capacity=%d,  cost=%f, price=%f)\n",
                item.getName(), item.getCapacity(), item.getCost(), item.getPrice());
        }
    }
    public class Item {
        private final String name;
        private final int quantity;
        private final double cost;
        private final double price;
    
        public Item (String name, int capacity, double cost, double price) {
            this.name = name;
            this.capacity = capacity;
            this.cost = cost;
            this.price = price;
        }
    
        // Getters omitted.
    }
    
    public class ItemUtils {
        /**
         * Read all lines from a file and maps them to items.
         *
         * @param path the path to the file, non-null
         * @return the list of items read from the file
         * @throws IOException if an I/O error occurs reading from the file or a malformed or unmappable byte sequence is read
         * @throws CustomRuntimeException if a line can't be mapped to an item
         */
        public static List<Item> readItems(Path path) throws IOException {
            Objects.requireNonNull(path);
    
            return Files.readAllLines(path, StandardCharsets.UTF_8)
                .stream()
                .map(ItemUtils::mapStringToItem)
                .collect(Collectors.toList());
    
        }
    
        /**
         * Maps a string to an item.
         *
         * @param str the string to map, non-null
         * @return the mapped item
         * @throws CustomRuntimeException if the string can't be mapped to an item
         */
        private static Item mapStringToItem(String str) {
            String[] tokens = str.split(",");
    
            if (tokens.length != 4) {
                String msg = String.format("Invalid item: 4 tokens expected, %d tokens found", tokens.length);
                throw new CustomRuntimeException(msg);
            }
    
            try {
                String name = tokens[0];
                int quantity = Integer.parseInt(tokens[1]);
                double cost = Double.parseDouble(tokens[2]);
                double price = Double.parseDouble(tokens[3]);
                return new Item(name, quantity, cost, price);
            } catch (NumberFormatException e) {
                throw new CustomRuntimeException("Invalid item: Type conversion failed", e);
            }
        }
    
        private ItemUtils() {
            // Utility class, prevent instantiation.
        }
    }
    
    /**
     * A custom runtime exception. Should be renamed to a more specific name.
     */
    public class CustomRuntimeException extends RuntimeException {
        public CustomRuntimeException(String msg) {
           super(msg);
        }
    
        public CustomRuntimeException(String msg, Throwable e) {
            super(msg, e);
        }