Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class DataHandler {
- private static final Path PATH = Paths.get(System.getProperty("user.home"), "Desktop", "data.txt");
- public static void main(String... args) {
- Person person = new Person("Male", "Tom", "Mr", "100");
- try {
- storeData(person);
- } catch (IllegalArgumentException | IllegalAccessException | IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- /**
- * Stores the users input into a text document
- */
- public static void storeData(Person user) throws IOException, IllegalArgumentException, IllegalAccessException {
- File file = PATH.toFile();
- if (!file.exists()) {
- file.createNewFile();
- }
- String output = user.toOutput();
- List<String> appendedLines = Arrays.asList(output);
- Files.write(PATH, appendedLines, StandardOpenOption.APPEND);
- }
- private static class Person {
- String gender, name, surname, age;
- private Person(String gender, String name, String surname, String age) {
- this.gender = gender;
- this.name = name;
- this.surname = surname;
- this.age = age;
- }
- public String toOutput() throws IllegalArgumentException, IllegalAccessException {
- Field[] fields = getClass().getDeclaredFields();
- StringBuilder output = new StringBuilder();
- for (Field field : fields) {
- Object value = field.get(this);
- output.append(field.getName()).append("=").append(value).append("\n");
- }
- return output.toString();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement