readObject的EOF异常

时间:2012-04-13 07:02:55

标签: java serialization eof objectoutputstream

我想知道是否还有检查ObjectInputStreamObjectOutputStream是否为空。我的意思是,在我的计划中。在第一次运行时,ObjectInputStream将使用其readObject()方法,因为仍然文件为空它给我一个EOF异常(文件结束)所以我想检查是否它是空的或没有然后摆脱异常:

我做得对吗?对于Serializing,我在客户端和服务器上创建了具有如下相同名称和属性的类。

public class KeyAdr implements Serializable{

 String adr;
 String key;


}
....

    static FileInputStream fIn=null;
    static ObjectInputStream oIn=null;
    private static KeyAdr test=new KeyAdr();

....

           fIn= new FileInputStream("d:\\someFile.ser");
           oIn = new ObjectInputStream(fIn);
           test= (KeyAdr) oIn.readObject(); 

编辑:

 static  File serAdrKey=new File("d:\\someFile.ser");
     static    ObjectOutputStream oOut;
     static    FileOutputStream fOut;
     static  final   Pattern WebUrlPattern = Pattern.compile (WebUrlRegex);
     private static String WebUrlStr;
     static KeyAdr letsDoIt= new KeyAdr();

....

 public static void openStreams() throws IOException
        {
         fOut= new FileOutputStream(serAdrKey);
     oOut = new ObjectOutputStream(fOut);

        }


        @Override
public void    beforeWindowOpen(NavigationEvent event) 
        {

                     temp=event.getURL().toString();


  Matcher WebUrlMatcher = WebUrlPattern.matcher (temp);
    if (WebUrlMatcher.matches ())
    {
        int n = WebUrlMatcher.groupCount ();
      for (int i = 0; i <= n; ++i) {
    WebUrlStr = WebUrlMatcher.group (i);

}

                    letsDoIt.adr=WebUrlStr;    

                    try {
                    oOut.writeObject(letsDoIt);

                } catch (IOException ex) {
                    Logger.getLogger(Cobratest2.class.getName()).log(Level.SEVERE, null, ex);
                }


                   try {
                oOut.flush();


                   } catch (IOException ex) {
                Logger.getLogger(Cobratest2.class.getName()).log(Level.SEVERE, null, ex);
            }

编辑2

fIn= new FileInputStream("d:\\someFile.ser");
PushbackInputStream input = new PushbackInputStream(fIn);
int c = input.read();
if(c != -1)
{
  input.unread(c);
  oIn = new ObjectInputStream(input);
  test = (KeyAdr) oIn.readObject();
  // ......
}

编辑3:

Edit2代码给了我跟踪堆栈跟踪的异常:

Exception in thread "main" java.io.EOFException
    at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2552)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1297)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
        at test.Test.processClient(Test.java:117)
            at test.Test.run(Test.java:92)
            at test.Test.main(Test.java:159)

2 个答案:

答案 0 :(得分:1)

  

我想检查它是否为空,然后摆脱异常:

为什么呢?那就是EOFException是 for。

答案 1 :(得分:0)

您可能需要先使用read方法检查是否至少有1个字节。

read()保证在到达流末尾时返回-1,如果第一个read()返回-1,则文件必须为空

附录: 使用FileInputStream,您应该能够标记/重置以避免丢失读取字节。

但是,您可能希望使用java.util.File预先检查文件的空白。