소프트웨어 개발/Java - Basic

serializable을 이용한 파일 저장, 불러오기

늘근이 2014. 5. 9. 16:31
public class UserDAOImplFile implements UserDAO {

	@Override
	public boolean insert(User user) {
		ObjectOutputStream out = null;

		try {

			ArrayList userList = selectUserList();
			userList.add(user);
			out = new ObjectOutputStream(new FileOutputStream("user.dat"));
			out.writeObject(userList);

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null)
					out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return false;
	}

	@Override
	public ArrayList selectUserList() {
		ObjectInputStream in = null;

		try {
			File f = new File("user.dat");

			if (f.exists()) {
				try {
					in = new ObjectInputStream(new FileInputStream("user.dat"));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				try {
					return (ArrayList) in.readObject();
				} catch (ClassNotFoundException | IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				return new ArrayList();
			}
		} finally {
			try {
				if (in != null)
					in.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return null;
	}

}//버그임