@Koshkin_I

Почему при десериализации null?

Сериализация вроде идет, во всяком случае в файле что-то есть. А при десириализации ни чего не поисходит. Поставил для проверки if(objectInputStream.available()!=0), в итоге он его делает где else.

public class ControlPoints extends MyKeyAdapter implements Externalizable {
    private static final long serialVersionUID = 1L;
    private ArrayList<Point>  points = new ArrayList<>(); 
    public ControlPoints(){}

    public ControlPoints(ArrayList<Point> points){
        this.points = points;
    }
    private  int index=0;
    public ArrayList<Point> getPoints() {
        return points;
    }
    private Point takeCoordinates(){
        PointerInfo a = MouseInfo.getPointerInfo();
        return a.getLocation();
    }
    public void addPoint(){
        points.add(index,takeCoordinates());
        index++;
    }
    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeObject(this.points);
    }
     @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
       points = (ArrayList<Point>) in.readObject();
    }
}

это код класса.

Кусок кода заполнения и сохранения:

frame.addKeyListener(new MyKeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyChar() == KeyEvent.VK_1) {
                        System.out.println("sssss");
                        controlPoints.addPoint();                        
                    }
                if (e.getKeyChar() == KeyEvent.VK_2){
                        Main.savePoints(controlPoints);
                        System.out.println("saved "+controlPoints.getPoints().get(0).getX());
                }


А это Main:

public static void main(String[] args) throws InterruptedException {
       ControlPoints p = new ControlPoints();

        JFrame.setDefaultLookAndFeelDecorated(true);
        new UiJFrame();

        try(FileInputStream fileInputStream = new FileInputStream("/home/ivan/IdeaProjects/src/prt1.txt");
                ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream)) {
            if(objectInputStream.available()!=0){
            while (objectInputStream.available() >0) {
                p = (ControlPoints) objectInputStream.readObject();
                System.out.println("ioheorg"+objectInputStream.available());
            }
}else System.out.println("ne if main 101");
        } catch (FileNotFoundException e) {
            System.out.println("ein catch");
        } catch (IOException e) {
            System.out.println("cvein catch");
        } catch (ClassNotFoundException e) {
            System.out.println("drein catch");
        }
        if (p!=null){
            System.out.println("Tuta "+p.getPoints().get(0).getX());
     }
       else{
     } System.out.println("null%%");

        MouseMoving mouseMoving = new MouseMoving(TIME_TO_WAIT);
        Thread thread = new Thread(mouseMoving);
        thread.start();
    }
    public static void savePoints(ControlPoints p) {
        try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(
                new FileOutputStream("/home/ivan/IdeaProjects/src/prt1.txt")
        )){
            objectOutputStream.writeObject(p.getPoints().get(0));
            objectOutputStream.writeObject(p.getPoints().get(1));
        } catch (FileNotFoundException e) {
            System.out.println("out catch 1");
        } catch (IOException e) {
            System.out.println("out catch 2");;
        }
    }

}
  • Вопрос задан
  • 96 просмотров
Пригласить эксперта
Ответы на вопрос 1
@Koshkin_I Автор вопроса
Проблему решил. Костыльно конечно и суть не совсем понял, но кому может сгодится.
При дисериализации в этом месте:
while (objectInputStream.available() >0) {
                p = (ControlPoints) objectInputStream.readObject();
                System.out.println("ioheorg"+objectInputStream.available());
            }
        } catch (FileNotFoundException e) {
            System.out.println("ein catch");
        } catch (IOException e) {
            System.out.println("cvein catch");
        } catch (ClassNotFoundException e) {
            System.out.println("drein catch");
        }

если убрать цикл, выскакивает IOException, с этим циклом получается описанная ситуация.
Добавил в цикл >=0, IOException вылетает, но и данные получаю. Добавил в цикл еще и break и теперь исключения нет.
Причина не понятна, но РАБОТАЕТ.)
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы