Advertisement
Guest User

example

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