Going mad here cant find what is problem. I am getting this from hint :
"Check why an exception occurs in the save/load methods."
package com.codegym.task.task20.task2002;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/*
Reading and writing to a file: CodeGym
*/
public class Solution {
public static void main(String[] args) {
// You can find your_file_name.tmp in your TMP directory or adjust outputStream/inputStream according to your file's actual location
try {
File yourFile = File.createTempFile("your_file_name", null);
OutputStream outputStream = new FileOutputStream(yourFile);
InputStream inputStream = new FileInputStream(yourFile);
CodeGym codeGym = new CodeGym();
// Initialize users field for the codeGym object here
codeGym.save(outputStream);
outputStream.flush();
CodeGym loadedObject = new CodeGym();
loadedObject.load(inputStream);
// Here check that the codeGym object is equal to the loadedObject object
outputStream.close();
inputStream.close();
} catch (IOException e) {
//e.printStackTrace();
System.out.println("Oops, something is wrong with my file");
} catch (Exception e) {
//e.printStackTrace();
System.out.println("Oops, something is wrong with the save/load method");
}
}
public static class CodeGym {
public List<User> users = new ArrayList<>();
public void save(OutputStream outputStream) throws Exception {
// Implement this method
PrintWriter writer = new PrintWriter(outputStream);
if (!users.isEmpty()) {
for (User u : users) {
writer.println(u.getFirstName());
writer.println(u.getLastName());
writer.println(u.getBirthDate().toString());
writer.println(u.isMale());
writer.println(u.getCountry().getDisplayName());
}
writer.flush();
}
}
public void load(InputStream inputStream) throws Exception {
// Implement this method
BufferedReader reader = new BufferedReader(new InputStreamReader( inputStream));
while (reader.ready()) {
User newUser = new User();
newUser.setFirstName(reader.readLine());
newUser.setLastName(reader.readLine());
SimpleDateFormat dateFormat = new SimpleDateFormat("dd MM yyyy");
Date d = dateFormat.parse(reader.readLine());
newUser.setBirthDate(d);
newUser.setMale(Boolean.parseBoolean(reader.readLine()));
String country = reader.readLine();
switch (country) {
case "United States":
newUser.setCountry(User.Country.UNITED_STATES);
case "United Kingdom":
newUser.setCountry(User.Country.UNITED_KINGDOM);
case "Other":
newUser.setCountry(User.Country.OTHER);
}
users.add(newUser);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CodeGym codeGym = (CodeGym) o;
return users != null ? users.equals(codeGym.users) : codeGym.users == null;
}
@Override
public int hashCode() {
return users != null ? users.hashCode() : 0;
}
}
}