Problem storing java object in file

Asked

Viewed 182 times

2

When I try to store an object in a binary file, the file with the extension .bin is created. However, when I try to access it by another class, it doesn’t even try to open the file .bin that I recorded my object. How to solve the problem?

Main Class

package ordenacao;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.Scanner;

public class Principal {

    public static void main(String[] args){
        lista l = new lista();
        lista aux = new lista();
        Scanner input = new Scanner(System.in);
        int x,i;

        for(i=0;i<4;i++){
            System.out.println("Digite um valor para empilhar:");
            x = input.nextInt();
            l.InsereInicio(x);
        }
        System.out.println("Dados Inseridos:");
        for(i=0;i<4;i++){
            x = l.removeInicio();
            aux.InsereFinal(x);
            System.out.println(x);
        }
        l = aux;
        try{
            OutputStream fileStream = new FileOutputStream("lista.bin");
            ObjectOutputStream os = new ObjectOutputStream(fileStream);
            os.writeObject(l);
            os.close();
            fileStream.close();
        }catch(IOException e){
            System.out.println("Erro 1");
        }
    }
}

Object I’m Wanting to store

package ordenacao;

import java.io.Serializable;

public class lista implements Serializable{
    elemento primeiro;
    elemento ultimo;

    public void InsereInicio(int valor){
        elemento novoprimeiro = new elemento();
        novoprimeiro.dado = valor;
        novoprimeiro.proximo = primeiro;
        primeiro = novoprimeiro;
        if(ultimo==null){
            ultimo = novoprimeiro;
        }
    }

    public void InsereFinal(int valor){
        elemento novoultimo = new elemento();
        novoultimo.dado = valor;
        novoultimo.proximo = null;
        if(primeiro == null){
            primeiro = novoultimo;
        }else{
            ultimo.proximo = novoultimo;
        }
        ultimo = novoultimo;
    }

    int estaVazio(){
        if(primeiro==null){
            return 1;
        }
        return 0;
    }

    int removeInicio(){
        if(estaVazio()==1){
            System.out.println("Esta vazio");
            return -1;
        }
        int k = primeiro.dado;
        primeiro = primeiro.proximo;
        if(primeiro==null){
            ultimo = null;
        }
        return k;
    }

    int removeFinal(){
        if(estaVazio()==1){
            return -1;
        }
        int k = ultimo.dado;
        elemento fim = primeiro;
        elemento penultimo = null;
        while(fim.proximo!=null){
            penultimo = fim;
            fim = fim.proximo;
        }
        if(penultimo!=null){
            penultimo.proximo = null;
            ultimo = penultimo;
        }else{
            primeiro = null;
            ultimo = null;
        }
        return k;
    }

    int remover(int pos){
        if((pos<0)||(estaVazio()==1)){
            return -1;
        }
        elemento anterior = new elemento();
        elemento atual = primeiro;
        int i;
        for(i=0;i<pos-1;i++){
            anterior = atual;
            atual = atual.proximo;
        }
        anterior.proximo = atual.proximo;
        atual = null;
        return 1;
    }
}

Reader who should read the data

package pacotejava;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;

public class PrincipalPacotenovo {
    public static void main(String[] args){
            int i;
            lista noval;
        try{
            InputStream conectar = new FileInputStream("lista.bin");
            ObjectInputStream os = new ObjectInputStream(conectar);
            Object obj = os.readObject();
            noval = (lista)obj;
            for(i=0;i<4;i++){
                System.out.println(noval.removeInicio());
            }
        }catch(IOException e){
            System.out.println("Erro 1");
        }catch(ClassNotFoundException e){
            System.out.println("Erro 2");
        }       
    }
}

-------Update-------

I managed to solve one of the problems when I played throws Ioexception the compiler ended up showing me the lines that were causing error(I had not closed the reader and I had forgotten to implement in one of the classes of my package the Serializable,and so I was able to compile the writer without problems),in relation to the reader I did not get the same luck,the error that appeared was the following:

Exception in thread "main" java.lang.ClassCastException: ordenacao.lista cannot be cast to pacotejava.lista
    at pacotejava.PrincipalPacotenovo.main(PrincipalPacotenovo.java:14)
C:\Users\Renan\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
FALHA NA CONSTRUÇÃO (tempo total: 0 segundos)
  • 1

    What are you trying to store in a file? What type? Try to detail better what you are trying to do, it is not very clear.

  • 1

    Welcome to [en.so]! What the mistake?

  • What do you mean "don’t even try"?

  • I am wanting to play my list I created (an object) in a file,and then access your data through another class,another package,the problem is that this program I implemented,is not able to read this data(even my program compiling normally),and to test,I tried to print the Exceptions caught by the catch to see if he was really giving error,and while executing he was printing what I put (ie he was giving IO error)(OBS.:sorry if I wasn’t clear,I had to leave in a hurry and ended up typing very fast)

1 answer

0

thank you for trying to help me,I realized the error after a little while thinking,the idea of recording in the file was that it could convert the object data into a serialized bit string and then while reading it return all the data stored in that object that was written in the file,the problem is that my object consists of "pointers",and when I recorded the list object,it recorded not only the data but also the "pointers" of the other objects that were on the list,and the problem was there,the Java "pointer" is referenced by the package in which the object(java file) found itself,and I was trying to refer for a different package,and while trying to do this it was giving error because it could not catch the reference,.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.