[英]copy / write contents of csv file to an array
我目前正在學習java,需要知道將csv文件的內容復制到數組中的最簡單方法,並再次將數組的內容復制到csv文件中。 所以目前我有一個CSV文件employee.csv,其中包含以下內容:
Name,Company,Experience.
現在,我需要檢索經驗大於2的員工,並將它們放在包含Name,Experience的另一個數組中。
我想將此數組寫入另一個名為results.csv的.csv文件中
實現這一目標的最佳方法是什么?
我認為您應該嘗試自己編寫代碼,而不是使用某些庫來為您完成此任務。 解析CSV文件對於“正在學習java”的人來說是一個很好的練習。
下面是一個用於保存Employees和方法來解析文件的類。 應該有更多錯誤檢查代碼。 如果文件中有一行沒有兩個逗號,則程序將崩潰。 我沒有為您處理經驗值檢查。 您可以在創建員工時檢查它,只有在滿足經驗要求時才將新對象添加到陣列,或者可以在寫入文件之前檢查該值。 為了簡化輸出到文件,我在Employee中編寫了一個CSVString方法。
public class Employee {
private String name;
private String company;
private int experience;
public Employee(String name, String company, int experience) {
this.name = name;
this.company = company;
this.experience = experience;
}
public Employee(String name, String company, String exp) {
this.name = name;
this.company = company;
try {
experience = Integer.parseInt(exp.trim());
}
catch(NumberFormatException utoh) {
System.out.println("Failed to read experience for " + name +
"\nCannot conver to integer: " + exp);
}
}
public String toCSVString() {
return name + "," + company + "," + experience;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public int getExperience() {
return experience;
}
public void setExperience(int experience) {
this.experience = experience;
}
}
現在從文件中讀取列表:
public static ArrayList<Employee> readEmployeeFile(File csvFile) {
ArrayList<Employee> list = new ArrayList<>();
Employee joe;
try {
Scanner in = new Scanner(csvFile);
String line;
while(in.hasNextLine()) {
line = in.nextLine().trim();
String[] col = line.split(",");
joe = new Employee(col[0],col[1],col[2]);
list.add(joe);
}
in.close();
}
catch(IOException ug) {
System.out.println("Error reading line: " + line);
System.out.println(ug);
}
return list;
}
您可以在這里查看如何讀取和寫入csv文件。
您只需在從employee.csv
讀取之后和寫入result.csv
文件之前檢查Experience
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.