I'm working with binary files, and I'm trying to write and read from them, I have these two functions :
public static void ListToBin (List<ModelVehicle> llModVeh,List<Vehicle> llVeh,String NomFitxerXml){
try {
File ff = new File("pruebas.bin");
RandomAccessFile raf = new RandomAccessFile(ff, "rw");
int q = llModVeh.size();
raf.writeInt(q);
for (int i = 0; i < q; i++) {
for(ModelVehicle m : llModVeh){
raf.writeChars(m.getNom() );
raf.writeChars(m.getMarca());
raf.writeShort(m.getCilindrada());
}
}
raf.close();
} catch (FileNotFoundException ex) {
} catch (IOException ex) {
}
}
and :
public static void BinToList(List<ModelVehicle> llModVeh,List<Vehicle> llVeh,String NomFitxerXml){
try {
llModVeh =new ArrayList();
File ff = new File("pruebas.bin");
RandomAccessFile raf = new RandomAccessFile(ff, "r");
int q = raf.readInt();
if (q < 0) {
throw new RuntimeException("Fitxer corrupte");
}
for (int i = 0; i < q; i++) {
String nom = raf.readUTF();
String marca = raf.readUTF();
Short cilindrada = raf.readShort();
}
raf.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
}
}
When i use the function ListToBin to write everything goes ok, but when i call the function BinToList i keep getting the error:
java.io.UTFDataFormatException: malformed input around byte 41
at java.io.DataInputStream.readUTF(DataInputStream.java:634) at java.io.RandomAccessFile.readUTF(RandomAccessFile.java:965) at info.infomila.Utils.BinToList(Utils.java:299) at info.infomila.Prova.main(Prova.java:84)
getMarca and getNom returns a string, getCilindrada a short!
You are writing with writeChars()
which writes exactly 2 bytes for each character. But you read with readUTF()
which reads 1 or more bytes per character (depending on the character).
Either use writeChars()
and readChars()
, or writeUTF()
and readUTF()
.