问题
e.g: (I took the first line of the external file)
Giant, Colgate Toothpaste, 4.50
I want to separate & save them in an array like this before/after I send them to the object & ArrayList.
mall[i] = "Giant";
product[i] = "Colgate Toothpaste";
price[i] = 4.50
p/s: I think I should do that because I need to alter the price in the future.
This is how my coding looks like right now.
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());}
}
Below is the content of the "product.in" file (external file)
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
If you think I provide you less information, just reply to this thread about it. I'll provide more.
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);
}
回答1:
Plain implementation without extra libraries like OpenCSV or similar would be
- Read the file line by line using
BufferedReader
andtry-with-resources
to make sure the file resource is closed automatically upon processing. - Split each line using
String.split
into columns - Create a
Product
item from the columns and add it to the list - Return the result list.
Aside note: it would be better to use price in int
cents than in double because the floating-point arithmetics is known to be imprecise.
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;
}
来源:https://stackoverflow.com/questions/65275606/is-there-any-ways-to-save-external-file-information-into-array-in-java