java - copy / write contents of csv file to an array -
java - copy / write contents of csv file to an array -
i learning java , need know easiest way re-create contents of csv file array , 1 time again re-create contents of array csv file. have csv file employee.csv contains following:
name,company,experience.
now need retrieve employees experience greater 2 , set them in array contains name, experience.
i want write array .csv file called results.csv
what best way accomplish this?
instead of using library task you, think should seek write code yourself. parsing csv file exercise "currently learning java."
below class hold employees , method parse file. there should more error checking code. if file has line without 2 commas in it, programme crash. didn't handle experience value check you. can either check create employees , add together new object array if meet experience requirement, or check value before writing file. simplify output file, wrote csvstring method in employee.
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; seek { experience = integer.parseint(exp.trim()); } catch(numberformatexception utoh) { system.out.println("failed read experience " + name + "\ncannot conver integer: " + exp); } } public string tocsvstring() { homecoming name + "," + company + "," + experience; } public string getname() { homecoming name; } public void setname(string name) { this.name = name; } public string getcompany() { homecoming company; } public void setcompany(string company) { this.company = company; } public int getexperience() { homecoming experience; } public void setexperience(int experience) { this.experience = experience; } }
now reading in list file:
public static arraylist<employee> reademployeefile(file csvfile) { arraylist<employee> list = new arraylist<>(); employee joe; seek { 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); } homecoming list; }
java
Comments
Post a Comment