我想知道是否有無論如何檢查ObjectInputStream
或ObjectOutputStream
是否爲空。我的意思是,在我的程序中。在第一次運行時,ObjectInputStream
將使用它的readObject()
方法,然後因爲該文件仍爲空,它會給我一個異常(文件結束),所以我想檢查它是否爲空或不是,然後擺脫異常:readObject的EOF異常
我在做對吧?對於序列化,我在客戶端和服務器端都使用了與下面相同的名稱和屬性。
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)
你在哪裏初始化ObjectOuputStream? – Phani 2012-04-13 07:20:52
@Phani我將它添加到問題中。我忘了寫在這裏 – lonesome 2012-04-13 07:28:14
看到我的編輯你的第二次編輯。 – EJP 2012-04-15 05:47:54