简体   繁体   English

如何序列化和反序列化 Java 中的 object?

[英]How to serialise and de-serialise an object in Java?

I need to modify class PrimeFactors so that it extends HashMap<Integer,ArrayList> and implements Serializable.我需要修改 class PrimeFactors 以便它扩展 HashMap<Integer,ArrayList> 并实现可序列化。

Let x be a number and y be an ArrayList containing the prime factors of x: add all <x,y> pairs to PrimeFactors and serialize the object into a new file.设 x 为数字,y 为包含 x 的质因子的 ArrayList:将所有 <x,y> 对添加到 PrimeFactors 并将 object 序列化为新文件。

Then write a method that de-serializes the PrimeFactors object from the file and displays the <x,y> pairs.然后编写一个方法,从文件中反序列化 PrimeFactors object 并显示 <x,y> 对。

Right now, I am completely stuck and unsure how to continue.现在,我完全陷入困境,不确定如何继续。 Any help would be greatly appreciated as I am very unfamiliar with this situation.任何帮助将不胜感激,因为我对这种情况非常不熟悉。

Here is my code so far:到目前为止,这是我的代码:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.ObjectOutputStream;


public class PrimeFactors2 extends HashMap<Integer,ArrayList<Integer>> implements Serializable {

public static void findFactor(int n) {
    System.out.print("Factors for the number " + n + " is: ");
    for (int i = n; i >= 1; i--) {
        if (n % i == 0)
            System.out.print(i + " ");
    }
}

public static boolean checkForPrime(int number) {

    boolean isItPrime = true;

    if (number <= 1) {
        isItPrime = false;
        return isItPrime;
    } else {
        for (int i = 2; i <= number / 2; i++) {
            if ((number % i) == 0) {
                isItPrime = false;
                break;
            }
        }

        return isItPrime;
    }

}

public static void main(String[] args) {

    String path = "/Users/benharrington/Desktop/primeOrNot.csv";
    String line = "";

    try {
        BufferedReader br = new BufferedReader(new FileReader(path));
        ArrayList<Integer> list = new ArrayList<Integer>();

        while ((line = br.readLine()) != null) {
            String[] values = line.split(",");

            for (String str : values) {
                int i = Integer.parseInt(str);
                boolean isItPrime = checkForPrime(i);

                if (isItPrime)
                    System.out.println(i + " is Prime");
                else
                    System.out.println(i + " is not Prime");

                if (isItPrime == false) {
                    list.add(i);

                }

            }
            for (int k : list) {
                System.out.println(" ");
                findFactor(k);

            }

        }

    } catch (FileNotFoundException e) {

        e.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }

  }
} 

What you did in your code is simply reading a file and parsing it.您在代码中所做的只是读取文件并解析它。

If you want to serialize and se-derialize an object, it can be done with the following code:如果要序列化和序列化 object,可以使用以下代码完成:

PrimeFactors2 primeFactors2 = // you object creation code here;
// i.e:
// PrimeFactors2 primeFactors2 = new PrimeFactors2();
// primeFactors2.setX1(2);
// primeFactors2.setX2(3);

try {
     FileOutputStream fileOut = new FileOutputStream("/tmp/obj.ser");
     ObjectOutputStream out = new ObjectOutputStream(fileOut);
     out.writeObject(primeFactors2);
     out.close();
     fileOut.close();
 } catch (Exception e) {
     e.printStackTrace();
 }

Then, in some context (same or another) in the same moment (or whenvever after you created the.ser object), you may de-serialize it with the following code:然后,在同一时刻(或在您创建 .ser 对象之后)的某些上下文(相同或另一个)中,您可以使用以下代码对其进行反序列化:

try {
     FileInputStream fileIn = new FileInputStream("/tmp/obj.ser");
     ObjectInputStream in = new ObjectInputStream(fileIn);
     PrimeFactors2 primeFactors2 = (PrimeFactors2) in.readObject();
     // YAY!!! primeFactors2 is an object with the same values you created before
     // i.e: primeFactors.getX1() is 2
     // primeFactors.getX2() is 3
     in.close();
     fileIn.close();
 } catch (Exception e) {
     e.printStackTrace();
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM