i am wondering if there is anyway to check if a ObjectInputStream or ObjectOutputStream is empty or not. i mean, in my program. at first time when it runs, the ObjectInputStream will use its readObject() method then because still the file empty it gives me an EOF exception( end of file) so i would like to check if it is empty or not then get rid off the exception:
And am i doing it right? for Serializing, i made the class with same name and attribute as below in both client and server.
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();
EDIT:
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);
}
Edit 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();
// ......
}
Edit 3:
the Edit2 codes gave me following exception with the stacktrace:
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)
You may want to use the
readmethod first to check if there is at least 1 byte.read()is guaranteed to return -1 when the end of the stream has been reached, if the very firstread()returns -1 the file must be emptyAddendum:
Using the FileInputStream you should be able to mark/reset to avoid losing the read byte.
You may however want to use java.util.File to check emptiness of the file beforehand.