Writing and reading files serialize an array

0

I have the following program:

package Exercici2;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Comarca implements Serializable {

    private String nom;
    private int habitants;

    public Comarca (String nom, int habitants){
        this.nom=nom;
        this.habitants=habitants;
    }
    public Comarca(){
        this.nom=null;
    }//Dar valor
    public void setNom(String comarca){nom=comarca;}
    public void setHabitants(int poblacio){ habitants=poblacio;}
    //COncultar valor
    public String getNom(){ return nom;}
    public int getHabitants(){return habitants;}

// ESCRIBIR FICHERO
    public static void EscriureFitxerObject () throws IOException , ClassNotFoundException{
        File f=new File("Datos.txt"); // Creamos el archivo
        FileOutputStream fos=new FileOutputStream(f);
        ObjectOutputStream oos=new ObjectOutputStream(fos);

        String comarca[] ={"Baixa Camp", "Segarra", "Bages", "Priorat", "Terra Alta",
            "Montsià", "Alt Camp","Anoia", "Maresme"};

        int poblacio[] = {190249, 22713, 184403, 9550, 12119, 69613, 44578, 117842, 437919};  

        oos.writeObject(comarca);

        oos.writeObject(poblacio);
        oos.close();
    }

   //LECTURA FICHERO! 
    public static void LlegirFitxerObject() throws ClassNotFoundException, IOException{
        ObjectInputStream ois=null;
        try{

        File f=new File("datos.txt");
        FileInputStream fis =new FileInputStream(f);
        ois=new ObjectInputStream(fis);
        while(true){
        //   ?????????????????          
        }            
        }catch(IOException io){
               System.out.println("Fin");
        }finally{
            ois.close();
               }
        }
        public static void main(String[] args) throws IOException, ClassNotFoundException{
            EscriureFitxerObject();
            LlegirFitxerObject();
    } }

I have problems with reading I do not know how to do it, I think the writing is fine unless you tell me otherwise.

I need to read the file I just wrote.

Can you help me?

For writing I am obliged to use ObjectOutputStream For reading I am forced to use ObjectInputStream.

    
asked by Montse Mkd 21.09.2017 в 21:15
source

2 answers

2

I think this will help you

The problem is that is to use the ObjectOutputStream and write an object oos.writeObject(...); are indicating that the file only open an object and that type so to write another would have to be another type for example double oos.writeDouble(0); so that these are separated the solution that implements in the code is to add the two objects comarca, poblaci in ArrayList<Object> woi = new ArrayList<>(); so store those 2 in the array and then call only that object ois.readObject();

at the end the array will bring you the 2 objects comarca, poblacio in arrangements as you defined them and well .. it's up to you how you want to use them.

public static void EscriureFitxerObject() throws IOException, ClassNotFoundException {

    File f = new File("{ruta_archivo}\Datos.txt"); 
    FileOutputStream fos = new FileOutputStream(f);
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    ArrayList<Object> woi = new ArrayList<>();

    String comarca[] = {"Baixa Camp", "Segarra", "Bages", "Priorat", "Terra Alta",
        "Montsià", "Alt Camp", "Anoia", "Maresme"};

    int poblacio[] = {190249, 22713, 184403, 9550, 12119, 69613, 44578, 117842, 437919};

    woi.add(comarca);
    woi.add(poblacio);

    oos.writeObject(woi);
    oos.close();
}

// ---

public static void LlegirFitxerObject() throws ClassNotFoundException, IOException {

    ObjectInputStream ois = null;
    try {

        File f = new File("{ruta_archivo}\Datos.txt");
        FileInputStream fis = new FileInputStream(f);
        ois = new ObjectInputStream(fis);
        ArrayList<Object> i = null;
        i = (ArrayList<Object>)ois.readObject();

        String[] comarca = (String[]) i.get(0);
        int[] poblacion = (int[]) i.get(1);

        for (int j : poblacion) {
            System.out.println(j);
        }
        System.out.println("------------------");
        for (String string : comarca) {
            System.out.println(string);
        }
        System.out.println(i);
    } catch (IOException io) {
        System.out.println(io.getMessage());
    } finally {
        ois.close();
    }
}
    
answered by 21.09.2017 / 22:55
source
1

Solution: Read the contents of the file in the same order it was written.

Going into detail, when reviewing the EscriureFitxerObject method, you have the following code:

String comarca[] = ...
int poblacio[] = ...
//escribes un arreglo de String
oos.writeObject(comarca);
//escribes un arreglo de primitivos
oos.writeObject(poblacio);

Then, in your reading method LlegirFitxerObject you should read as is:

//lees el arreglo de String
String[] comarca = (String[]) ois.readObject();
//lees el arreglo de primitivos
int[] poblacio = (int[]) ois.readObject();
//no es necesario leer "eternamente"
//while (true) { 
//}

When would you read the contents of a binary file "eternally", or in other words, using while(true) ? You do this yes and only yes you wrote the file with an unknown number of objects (preferably of the same class). The validation offered by Java for these cases is that, if it is at the end of the file, then when trying to read it will throw an exception of the type EOFException . An example:

ObjectOutputStream oos = ... //escribe a un archivo X
String[] datos = { "hola", "mundo" };
//cantidad de elementos escritos "desconocida"
for (String s : datos) {
    oos.writeObject(s);
}

//...

ObjectInputStream ois = ... //leyendo del archivo X
//puesto que no sabes cuántos elementos hay, conviene usar una lista
List<String> datos = new ArrayList<>();
try {
    datos.add((String)ois.readObject());
} catch (EOFException e) {
    //fin del archivo
    System.out.println("Fin del archivo. No más contenido");
} catch (IOException e) {
    System.out.println("Error desconocido. Revisar.");
    e.printStackTrace(System.out);
}
System.out.println(datos);
    
answered by 22.09.2017 в 08:16