在java中有没有办法将外部文件“信息”保存到数组中?

ruarlubt  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(261)

e、 g:(我取了外部文件的第一行)

Giant, Colgate Toothpaste, 4.50

在将它们发送到object&arraylist之前/之后,我想将它们分离并保存在这样的数组中。

mall[i] = "Giant";
product[i] = "Colgate Toothpaste";
price[i] = 4.50

附言:我想我应该这样做,因为我将来需要改变价格。
这就是我的代码现在的样子。

public static void readFile(ArrayList<Product> productList) throws Exception {
        try {
            productList.clear(); //clear the list! or remove all elements from the list!
            // Coding Here
        }
        catch(Exception e) { System.err.println(e.getMessage());}
    }

下面是“product.in”文件(外部文件)的内容

Giant, Colgate Toothpaste, 4.50
Giant, Dashing Deodorant, 6.55
Giant, Adidas Deodorant, 7.55
Giant, Dettol Hand-sanitiser, 10.00
Giant, Sokubutso Shower Foam, 15.00
Tesco, Colgate Toothpaste, 4.55
Tesco, Dettol Hand-sanitiser, 7.00
Tesco, Sokubutso Shower Foam, 15.05
Tesco, Adidas Deodorant, 7.45
Tesco, Dashing Deodorant, 5.45
TF, Sokubutso Shower Foam, 15.05
TF, Dettol Hand-sanitiser, 9.50
TF, Adidas Deodorant, 8.55
TF, Dashing Deodorant, 7.55
TF, Colgate Toothpaste, 5.00

如果你认为我提供给你的信息少了,就回复这个帖子吧。我会提供更多。 edited: add product class ```
class Product {
private String store;
private String item;
private double price;

public Product(String store, String item, double price) {
    this.setStore(store);
    this.setItem(item);
    this.setPrice(price);
}
dy1byipe

dy1byipe1#

没有额外的库(如opencsv或类似的库)的简单实现是可行的
使用逐行读取文件 BufferedReader 以及 try-with-resources 确保文件资源在处理时自动关闭。
使用拆分各行 String.split
创建 Product 项目并将其添加到列表中
返回结果列表。
旁注:最好用价格 int 因为众所周知,浮点运算是不精确的。

import java.io.*;
import java.util.*;
// ...

public static List<Product> readFile(String csvFile) throws Exception {
    List<Product> result = new ArrayList<>();
    try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
        String line;
        while((line = br.readLine()) != null) {
            String[] cols = line.split("\\s*,\\s*"); // split by comma and optional spaces
            assert cols.length > 2;  // make sure the line contains at least 3 columns
            Product product = new Product(cols[0], cols[1], Double.parseDouble(cols[2]));
            result.add(product);
        }
    }
    catch(Exception e) {
        System.err.println(e.getMessage());
        throw e;
    }

    return result;
}

相关问题