【问题标题】:Is there any ways to save external file "information" into array in java?有没有办法将外部文件“信息”保存到java中的数组中?
【发布时间】:2020-12-13 12:30:59
【问题描述】:

例如:(我取了外部文件的第一行)

Giant, Colgate Toothpaste, 4.50

我想在将它们发送到对象和 ArrayList 之前/之后将它们分开并保存在这样的数组中。

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

p/s:我认为我应该这样做,因为我需要在未来改变价格。

这就是我的编码现在的样子。

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);
    }

【问题讨论】:

  • 魔术关键字是 JSON。看一看:stackoverflow.com/questions/26605763/…
  • 为什么不省略数组,直接把每一行变成Product?当然,如果需要,您以后应该能够更改Product 的价格?
  • @Melvin 我不认为我可以使用 JSON,因为外部文件 (product.in) 已像上面的线程中那样预先格式化。
  • @KevinAnderson 我一直在将产品类更新到线程中。我不能因为它而省略数组。我需要向 Product 类发送 3 个数据
  • 我认为我应该先将它们分开,然后再将它们发送到另一个班级

标签: java arrays arraylist filereader


【解决方案1】:

没有像 OpenCSV 或类似的额外库的简单实现将是

  1. 使用BufferedReadertry-with-resources逐行读取文件,确保文件资源在处理时自动关闭。
  2. 使用String.split 将每一行拆分为列
  3. 从列中创建一个Product 项目并将其添加到列表中
  4. 返回结果列表。

旁注:使用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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-24
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 2021-12-18
    • 2017-07-20
    • 2019-06-21
    • 1970-01-01
    相关资源
    最近更新 更多