2016-07-28 67 views
-1

我试图从txt文件中读取学生的地图,之后我向地图中添加一个新学生(现在比以前更大)并将其保存回文件。关闭程序并重新加载文件中的数据后,新学生未保存。难以将文件写入文件

HashMap<String, Student> studentObj = new HashMap<>(SIZE); 

try { 
    ObjectInputStream in = new ObjectInputStream(new FileInputStream(DEFAULT_FILE_NAME)); 
    studentObj = (HashMap<String, Student>) in.readObject();    
    studentObj.put(student.getStudentID(), student); 

    ObjectOutputStream out; 
    out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(DEFAULT_FILE_NAME))); 
    out.writeObject(studentObj); 
    out.flush(); 
    System.out.println("here " + studentObj.size()); 
    in.close(); 
    out.close(); 
} catch (IOException e) { 
    throw new Exception("FILE IS NOT CREATED"); 
} catch (ClassNotFoundException e) { 
    throw new Exception("CLASS NOT FOUND EXCPETION"); 
} 
+2

打印异常的堆栈跟踪:'e.printStackTrace()'。这会告诉你遇到的问题。 –

+0

我建议处理数据并保存,例如作为文本文件而不是使用ObjectOutputStream。你可以for循环,将数据保存到数组中,并以一种可以让你再次正确读取它们的方式保存它们。 – xdevs23

+2

捕捉各种异常然后将它们作为基本异常抛出并没有真正的意义。要么处理这些异常,要么让你的方法抛出那些特定的异常,或者简单地抛出异常,如果你不关心它们是什么类型的话。如果您打印异常的堆栈跟踪,那么您将看到问题所在。 – ManoDestra

回答

0

我的代码没问题。问题是,将对象保存到文件后,我关闭了应用程序并再次打开它。然后,构造函数创建一个覆盖旧文件的新文件。我添加了一个if语句来第一次创建文件。我用txt使它简单快速,因为它只是一项小任务。我喜欢使用XML文件:)而且,JAVA可以保存对象。

0

我@同意xdevs23

而是将数据保存到数组(这将使用更多的内存),你可以写

/*import java.io.BufferedWriter; 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.OutputStreamWriter; 
import java.io.Writer;*/ 

HashMap<String, Student> studentObj = new HashMap<>(SIZE); 

try{ 

    ObjectInputStream in = new ObjectInputStream(new FileInputStream(DEFAULT_FILE_NAME)); 
    studentObj = (HashMap<String, Student>) in.readObject();    
    studentObj.put(student.getStudentID(), student); 
    in.close(); 
    System.out.println("here " + studentObj.size()); 

    FileOutputStream fos = new FileOutputStream(DEFAULT_FILE_NAME); 
    OutputStreamWriter osw = new OutputStreamWriter(fos); 
    Writer w = new BufferedWriter(osw); 

    // Iterate using YOUR hash keys 
    for(int i = 0; i < studentObj.size(); i++){ 
     w.write(studentObj.get(i).getString()); 
     w.write(studentObj.get(i).getStudent()); 
    } 

    w.close(); 

     catch (IOException e) { 
     throw new Exception("FILE IS NOT CREATED"); 
    } catch (ClassNotFoundException e) { 
     throw new Exception("CLASS NOT FOUND EXCPETION"); 
    } 
} 

而只是写从ObjectInputStream中直接拉数据到文件