Prosty projekt w ramach nauki wlasnej. W sumie to ktos mi kiedys to zadal, a wczoraj zrobilem.
Bez używania żadnej biblioteki do parsowania. W sumie pewnie sprobuje zrobic to samo z apache commons.
Uzyłem try with resources, zeby bylo autoclosable.
Prosilbym o jakis komentarz. Czy uzycie main, 2 razy we writer i parser jest ok, czy powinienem to jakos inaczej zrobic?
Treść napisał(a)
Stwórz klasy:
- Person (np. Imie i Nazwisko, PESEL, Adres)
- CSVWriter
- CSVParser
Stworz na dysku plik *.csv z przykladowymi danymi dla klasy Person.
Napisz parser plikow csv dla klasy Person i writer dopisujący do istniejącego pliku kolejne obiekty klasy Person w formacie csv.
id - w sensie pesel.
Klasa Person:
public class Person {
private long id;
private String name;
private String address;
public Person(long id, String name, String address) {
this.id = id;
this.name = name;
this.address = address;
}
@Override
public String toString() {
return id + ", " + name + ", " + address;
}
}
Klasa CSVWriter:
import java.io.*;
public class CSVWriter {
public static void main(String[] args) {
try (FileOutputStream outputStream = new FileOutputStream("people.csv", true); //starczylo dopisac true by dopisywalo na koncu...
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream))) {
Person person1 = new Person(86010569198L, "Andrzej Kowalski", "ul. Sosnowa 15");
Person person2 = new Person(97010569198L, "Janusz Migdalski", "ul. Kawowa 34");
Person person3 = new Person(80010569198L, "Arek Patrycjowy", "ul. Maslowa 107");
bufferedWriter.write(person1.toString());
bufferedWriter.newLine();
bufferedWriter.write(person2.toString());
bufferedWriter.newLine();
bufferedWriter.write(person3.toString());
bufferedWriter.newLine();
} catch (FileNotFoundException e) {
System.out.println("File not found ");
} catch (IOException e) {
System.out.println("Unable to write the file ");
}
}
}
Klasa CSVParser:
import java.io.*;
public class CSVParser {
public static void main(String[] args) {
try (FileInputStream input = new FileInputStream("people.csv");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input))) {
String strLine;
String cvsSplitBy = ",";
while ((strLine = bufferedReader.readLine()) != null) {
String[] people = strLine.split(cvsSplitBy);
System.out.println("Person [PESEL= " + people[0]
+ " , name=" + people[1] + " , address=" + people[2] + "]");
if (people[0].length() != 11)
throw new Exception("Error: invalid id number"); //wyrzuca błąd w przypadku wpisania złego nr pesel
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
dodanie znacznika <quote>
- @furious programming