Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Demo object1 = new Demo(100,"saran");
- Demo object2 = new Demo(20 ,"nivas");
- ArrayList<Demo> list=new ArrayList<>();
- try {
- FileOutputStream file=new FileOutputStream("C:\Users\SARANNIVAS\Documents\file\obj");
- ObjectOutputStream out=new ObjectOutputStream(file);
- list.add(object1);
- list.add(object2);
- out.writeObject(list);
- out.close();
- file.close();
- System.out.println("object has been serialized");
- } catch(IOException ex)
- {
- ex.printStackTrace();
- System.out.println("exception is caught");
- }
- try {
- FileInputStream file=new FileInputStream("C:\Users\SARANNIVAS\Documents\file\obj");
- ObjectInputStream in=new ObjectInputStream(file);
- ArrayList<Demo> list1=new ArrayList<>();
- list1=(ArrayList<Demo>)in.readObject();
- for(Demo d:list1) {
- System.out.println(d.a);
- System.out.println(d.b);
- }
- } catch(IOException ex) {
- System.out.println("IOException is caught");
- }
- public static void main(String... args) {
- Demo object1 = new Demo(100, "saran");
- Demo object2 = new Demo(20, "nivas");
- serialize(object1, object2);
- List<Demo> collections = load();
- //search
- List<Demo> result = search(collections, "saran");
- //match result
- if (Objects.nonNull(result))
- result.stream().forEach(System.out::println);
- }
- public static List<Demo> search(List<Demo> collections, String name) {
- if (Objects.isNull(collections) || collections.isEmpty()) return null;
- return collections.stream().filter(itm -> itm.b.equals(name)).collect(Collectors.toList());
- }
- public static void serialize(Demo... objects) {
- try {
- FileOutputStream file = new FileOutputStream("/home/jst/obj");
- ObjectOutputStream out = new ObjectOutputStream(file);
- if (Objects.nonNull(objects)) {
- List<Demo> collect = Arrays.stream(objects).collect(Collectors.toList());
- out.writeObject(collect);
- out.close();
- file.close();
- System.out.println("object has been serialized");
- }
- } catch (
- IOException ex) {
- ex.printStackTrace();
- System.out.println("exception is caught");
- }
- }
- public static List<Demo> load() {
- try {
- FileInputStream file = new FileInputStream("/home/jst/obj");
- ObjectInputStream in = new ObjectInputStream(file);
- return (ArrayList<Demo>) in.readObject();
- } catch (Exception ex) {
- System.out.println("IOException is caught");
- return null;
- }
- }
- public static class Demo implements Serializable {
- private int a;
- private String b;
- public Demo(int a, String b) {
- this.a = a;
- this.b = b;
- }
- public int getA() {
- return a;
- }
- public void setA(int a) {
- this.a = a;
- }
- public String getB() {
- return b;
- }
- public void setB(String b) {
- this.b = b;
- }
- @Override
- public String toString() {
- return "Demo{" +
- "a=" + a +
- ", b='" + b + ''' +
- '}';
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement