So i looked over a couple of solutions but none of them worked for me. Thanks for some folks i got the infinite cycle right in the end, but it still doesnt work for me. I want to read a file "output.txt" into a list of objects. So i provide the remaining codes since i thought they wouldnt help at all...
try {
List<House> listH = new ArrayList<>();
boolean cont = true;
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("output.txt"));
while(cont)
{
House house = (House) ois.readObject();
if(house != null)
listH.add(house);
else
cont = false;
}
ois.close();
mainmenu();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
The writing code:
try {
FileWriter writer = new FileWriter("output.txt");
for(House str : listH)
{
writer.write(String.valueOf(str) + "\n");
}
writer.close();
System.out.println("Successful writing");
} catch (IOException e) {
e.printStackTrace();
System.out.println("Couldn't write");
}
The House Object:
public class House {
String address;
double area;
boolean garage;
public House(String address, double area, boolean garage){
this.address=address;
this.area = area;
this.garage = garage;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public double getArea() {
return area;
}
public void setArea(double area) {
this.area = area;
}
public boolean isGarage() {
return garage;
}
public void setGarage(boolean garage) {
this.garage = garage;
}
@Override
public String toString() {
return address + ";" + area + ";" + garage;
}
}
The error messages are the following:
java.io.StreamCorruptedException: invalid stream header: 3134313B at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:866) at java.io.ObjectInputStream.(ObjectInputStream.java:358)
You have three main problems:
hasnext
in the while condition and readline
to 'manually' construct a house object from string values.