Para un proyecto universitario, tengo que guardar un mapa hash de Listas en un archivo binario. Entonces tengo que poder cargarlo de nuevo, pero tengo algunos problemas. Guardará mi archivo pero no lo cargará. Aquí está mi código:
Esto es ahorro:
private static void storeRec() { try { File f = new File("recommendation.dat"); if(!f.exists()) { f.createNewFile(); } FileOutputStream fos=new FileOutputStream(f); ObjectOutputStream oos=new ObjectOutputStream(fos); oos.writeObject(localStore); oos.flush(); oos.close(); fos.close(); System.out.println("Recommendation read to File"); } catch (IOException ex) { Logger.getLogger(Project2.class.getName()).log(Level.SEVERE, null, ex); } }Este es el código de carga:
List<Recommendation> newmovies = new ArrayList<>(); try { File f = new File("recommendation.dat"); if(f.exists()) { DataInputStream dis = new DataInputStream(new FileInputStream(f)); /*FileInputStream streamIn = new FileInputStream(f); ObjectInputStream dis = new ObjectInputStream(streamIn);*/ while(dis.available()>0) { byte[] titleBytes = new byte[32]; dis.read(titleBytes); String title = new String(titleBytes); byte[] queryBytes = new byte[32]; dis.read(queryBytes); String query = new String(queryBytes); byte[] directorBytes = new byte[32]; dis.read(directorBytes); String director = new String(directorBytes); byte[] summaryBytes = new byte[64]; dis.read(summaryBytes); String summary = new String(summaryBytes); byte[] categoryBytes = new byte[18]; dis.read(categoryBytes); String category = new String(categoryBytes); //String category = dis.readUTF(); double rating = dis.readDouble(); int release = dis.readInt(); byte[] castBytes = new byte[64]; dis.read(castBytes); String cast= new String(castBytes); ArrayList<String> castArrayList = new ArrayList<>(Arrays.asList(cast.split(","))); int myRating = dis.readInt(); byte[] commentsBytes = new byte[32]; dis.read(commentsBytes); String myComments = new String(commentsBytes); newmovies.add(new Recommendation(title,query,director,summary,release,category,rating,castArrayList,myRating,myComments)); //System.out.println(newmovies); localStore.put(query, newmovies); } }LocalStore es un hashmap al que me gustaría agregar los datos del archivo. La clave es la Consulta. Por alguna razón no se agregará al mapa.
Cualquier ayuda sería muy apreciada.
Debe usar un ObjectInputStream en un archivo creado por ObjectOutputStream y readObject() para leer un objeto escrito por writeObject() .
Y available() no es una prueba válida para el final de la transmisión. Consulte el Javadoc. Tienes que atrapar EOFException .