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.