I'm trying to get it to read a .txt file that I've created by writing it to binary with other code. I don't understand why it gives me an error and doesn't read it.
this is the start
DatosUsuario login = new DatosUsuario();
// Creamos un objeto de tipo fila para asignarle un archivo
File file = new File("login.txt");
try {
// Para poder leer utilizaremos un FileInputStream pasandole
// como referencia el archivo de tipo File.
FileInputStream fileIS = new FileInputStream(file);
// Declaramos una variable objeto del tipo ObjectInputStream
ObjectInputStream read;
// Creamos un bucle para leer la información
// Mientras haya bytes en el archivo.
while(fileIS.available()>0) {
read = new ObjectInputStream(fileIS);
// En una variable objeto de tipo Persona almacenaremos
// el objeto leido de tipo Object convertido en un objeto
// de tipo persona
DatosUsuario loginRead = (DatosUsuario) read.readObject();
// Imprimimos el objeto leido en consola
System.out.println(loginRead);
}
}catch (IOException e) {
e.printStackTrace();
}
this is the class
public class DatosUsuario {
private String usuario;
private String contrasenna;
public String getUsuario() {
return usuario;
}
public void setUsuario(String usuario) {
this.usuario = usuario;
}
public String getContrasenna() {
return contrasenna;
}
public void setContrasenna(String contrasenna) {
this.contrasenna = contrasenna;
}
}
maybe there is a better way to do it without using classes, all I want is to be able to read that file, use classes in case it was more organized. This is the error it gave me
Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast
to class ACT5.DatosUsuario (java.lang.String is in module java.base of loader 'bootstrap';
ACT5.DatosUsuario is in unnamed module of loader 'app')
at ACT5.Start.main(Start.java:36)
Line 36 of start says this:
DatosUsuario loginRead = (DatosUsuario) read.readObject();
The error indicates a conversion problem:
The ObjectInputStream method returns a value of type
readObject()
, it can't be converted directly to , so just get this value as and print it.String
DatosUsuario
String
You comment that now you have the error:
Remember that if you read with
readObject()
you must write withwriteObject()
, it seems to me that your fileLogin.txt
does not contain the information to be able to deserialize and build an objectDatosUsuario
, check this example:In the end I solved it using this code that I learned watching several tutorials and my teacher answered me with an example. The class
DatosUsuarios
changes it topersona
.the class to write
the class to read
the person class