2014-02-11 192 views
0

我从文件Java中读取对象时遇到问题。从文件读取对象

filearraylist<projet>

这是保存对象的代码:

try { 
    FileOutputStream fileOut = new FileOutputStream("les projets.txt", true); 
    ObjectOutputStream out = new ObjectOutputStream(fileOut); 

    for (projet a : file) { 
     out.writeObject(a); 
    } 
    out.close(); 
} catch (Exception e) { 
    e.printStackTrace(); 
} 

这是阅读的对象从文件::写作正常工作的代码

try { 
    FileInputStream fileIn = new FileInputStream("les projets.txt"); 
    ObjectInputStream in = new ObjectInputStream(fileIn); 

    while (in.available() > 0){ 
     projet c = (projet) in.readObject(); 

     b.add(c); 
    } 

    choisir = new JList(b.toArray()); 
    in.close(); 
} catch (Exception e) { 
    e.printStackTrace(); 
} 

。问题是阅读......它不读任何对象(projet)可能是什么问题?

+0

嗨,你有没有得到你的代码的'e.printStackTrace()'行打印的任何异常消息?如果是这样,请你将跟踪贴到问题上。 – mico

+0

sry我有编辑我的问题cz任何对象重新注册! – user3285843

+0

@mico noo打印任何异常消息 – user3285843

回答

0

正如EJP在评论中提到的和this SO post。如果您打算在单个文件中编写多个对象,则应编写自定义ObjectOutputStream,因为在写入第二个或第n个对象头信息时,该文件将被损坏。
正如EJP建议写为ArrayList,由于ArrayList已经是Serializable,所以你不应该有问题。作为

out.writeObject(file)并重新读取为ArrayList b = (ArrayList) in.readObject();
由于某种原因,如果你不能把它写成ArrayList中。创建custome ObjectOutStream为

class MyObjectOutputStream extends ObjectOutputStream { 

public MyObjectOutputStream(OutputStream os) throws IOException { 
    super(os); 
} 

@Override 
protected void writeStreamHeader() {} 

}

,改变你的writeObject作为

try { 
     FileOutputStream fileOut= new FileOutputStream("les_projets.txt",true); 
     MyObjectOutputStream out = new MyObjectOutputStream(fileOut); 

     for (projet a : file) { 
    out.writeObject(a); 
} 
     out.close(); 
    } 

    catch(Exception e) 
    {e.printStackTrace(); 

}

,改变你的readObject作为

ObjectInputStream in = null; 
    try { 
     FileInputStream fileIn = new FileInputStream("C:\\temp\\les_projets1.txt"); 
     in = new ObjectInputStream(fileIn); 

     while(true) { 
      try{ 
       projet c = (projet) in.readObject(); 
       b.add(c); 
      }catch(EOFException ex){ 
       // end of file case 
       break; 
      } 

     } 

    }catch (Exception ex){ 
     ex.printStackTrace(); 
    }finally{ 
     try { 
      in.close(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 
+0

关闭时出错() potentiel.java:263:错误:未报告的异常IOException;必须被捕获或被宣布为抛出 \t \t \t \t ex.printStackTrace(); } finally {in.close(); } – user3285843

+0

在读取对象的finally块中应该添加try catch。我修改了代码。 – Mani

+0

使用try-with-resources来处理关闭流。 – Pshemo