我想知道是否有任何方法可以检查 a ObjectInputStream
orObjectOutputStream
是否为空。我的意思是,在我的程序中。第一次运行时,ObjectInputStream
将使用它的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)