我想知道是否有无论如何检查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