22
Июл
2021

Проблема с использованием Externalizable

Есть блок инициализации в основном классе:

private ScoreSheet ss;
{
    File file = new File("table.bin");
    if(!file.exists()) {
    try {
        file.createNewFile();
        ss = new ScoreSheet();
        try(FileOutputStream fos = new FileOutputStream("table.bin");
                ObjectOutputStream oos = new ObjectOutputStream(fos)){
               oos.writeObject(ss);
        }           
    }
    catch (IOException ex) {
        ex.printStackTrace();
        }
    }
    else {
    try(FileInputStream fis = new FileInputStream("table.bin");
            ObjectInputStream ois = new ObjectInputStream(fis)){
        ss = (ScoreSheet) ois.readObject();
    }
    catch (IOException | ClassNotFoundException ex) {
        ex.printStackTrace();
        }
    }
}

в строке ss = (ScoreSheet) ois.readObject(); происходит вылет с Exception in thread "AWT-EventQueue-0" java.lang.ExceptionInInitializerError

ниже по стек-трейсу ещё есть Caused by: java.lang.NullPointerException at java.util.Base64$Decoder.decode(Base64.java:549)

Код класса вызываемого объекта:

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.List;

public class ScoreSheet implements Externalizable {

private List<PlayerStats> players = new ArrayList<>();

public List<PlayerStats> getList() {
    return players;
}

public ScoreSheet() {}

@Override
public void writeExternal(ObjectOutput out) throws IOException {
    for(PlayerStats current: players) {
        out.writeObject(current);           
    }
}

@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
      for (int i = 0; i < players.size(); i++) {
          PlayerStats current = (PlayerStats) in.readObject();
          players.add(current);
          }
     }  
}

Код класса объектов из листа:

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Calendar;
import java.util.Date;

public class PlayerStats implements Externalizable, Comparable<PlayerStats> {

private String name;
private String pass;
private Integer score = 0;
private Date date = new Date();
    
public PlayerStats(String name, String pass) {
    this.name = name;
    this.pass = pass;
}

public PlayerStats() {}

public void setScore(Integer score) {
    this.score = score;
}
public String getName() {
    return name;
}
public String getPass() {
    return pass;
}
public Integer getScore() {
    return score;
}
public String getDate() {
    
    String pattern = "dd/MM/yyyy";
    DateFormat df = new SimpleDateFormat(pattern);

    Date today = Calendar.getInstance().getTime();

    String reportDate = df.format(today);
    
    return reportDate;
}

@Override
public int compareTo(PlayerStats another) {
    return score.compareTo(another.score);
}   
@Override
public String toString() {
    return "Player [name=" + name + ", date=" + date + ", score=" + score + "]";
}

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((name == null) ? 0 : name.hashCode());
    result = prime * result + ((pass == null) ? 0 : pass.hashCode());
    return result;
}
@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    PlayerStats other = (PlayerStats) obj;
    if (name == null) {
        if (other.name != null)
            return false;
    } else if (!name.equals(other.name))
        return false;
    if (pass == null) {
        if (other.pass != null)
            return false;
    } else if (!pass.equals(other.pass))
        return false;
    return true;
}

@Override
public void writeExternal(ObjectOutput out) throws IOException {

       out.writeObject(this.getName());
       out.writeObject(this.encryptString(this.getPass()));
       out.writeObject(this.getScore());
       out.writeObject(this.getDate());     
}
private Object encryptString(String pass2) {
    return Base64.getEncoder().encodeToString(pass.getBytes());
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {

       name = (String) in.readObject();
       pass = this.decryptString((String) in.readObject());
       score = (Integer) in.readObject();
       date = (Date) in.readObject();
}
private String decryptString(String readObject) {
    return new String(Base64.getDecoder().decode(pass));
    }   
}

когда вместо Externalizable был везде Serializable, то всё отлично работало.

Источник: https://ru.stackoverflow.com/questions/1307792/%D0%9F%D1%80%D0%BE%D0%B1%D0%BB%D0%B5%D0%BC%D0%B0-%D1%81-%D0%B8%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5%D0%BC-externalizable

Тебе может это понравится...

Добавить комментарий