Advertisement
Guest User

example

a guest
May 4th, 2016
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. public class DataHandler {
  2.  
  3. private static final Path PATH = Paths.get(System.getProperty("user.home"), "Desktop", "data.txt");
  4.  
  5. public static void main(String... args) {
  6. Person person = new Person("Male", "Sneaky", "Mr", "100");
  7.  
  8. try {
  9. storeData(person);
  10. } catch (IllegalArgumentException | IllegalAccessException | IOException e) {
  11. // TODO something relative to the exception at hand.
  12. e.printStackTrace();
  13. }
  14. }
  15.  
  16. public static void storeData(Person user) throws IOException, IllegalArgumentException, IllegalAccessException {
  17. File file = PATH.toFile();
  18.  
  19. if (!file.exists()) {
  20. file.createNewFile();
  21. }
  22. List<String> appendedLines = Arrays.asList(user.serialize());
  23.  
  24. Files.write(PATH, appendedLines, StandardOpenOption.APPEND);
  25. }
  26.  
  27. private static class Person {
  28.  
  29. String gender, name, surname, age;
  30.  
  31. private Person(String gender, String name, String surname, String age) {
  32. this.gender = gender;
  33. this.name = name;
  34. this.surname = surname;
  35. this.age = age;
  36. }
  37.  
  38. public String serialize() throws IllegalArgumentException, IllegalAccessException {
  39. Field[] fields = getClass().getDeclaredFields();
  40.  
  41. StringBuilder output = new StringBuilder();
  42.  
  43. for (Field field : fields) {
  44. Object value = field.get(this);
  45.  
  46. output.append(field.getName()).append("=").append(value).append("\n");
  47. }
  48. return output.toString();
  49. }
  50.  
  51. }
  52.  
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement