예 : (외부 파일의 첫 번째 줄을 가져 왔습니다)
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);
}
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;
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다