I have taken in a text file and converted it into a binary by writing the objects to a binary file, then i am attempting to read from the binary file, which works all the way through till the last record and then it throws the IO exception and never gets to my last print statement.
Below is my code that is triggering the error
try
{
ObjectInputStream objinputStream2 = new ObjectInputStream(new FileInputStream("binaryFile"));
for (int run = 0; run<count;count++)
{
Record readone = (Record) objinputStream2.readObject();
System.out.print(readone);
System.out.println("");
}
System.out.println("Reading completed for all" + count + " records. ");
// objinputStream2.close();
}
catch(FileNotFoundException e){ // Catches object
System.out.println("Sorry File not found"); // Error Message
}
catch(ClassNotFoundException e){ // Catches object
System.out.println("Sorry class not found"); // Error Message
}
catch(IOException e){ // Catches object
System.out.println("Problem with file output."); // Error Message
e.printStackTrace();
}
any help is appreciated
Stack trace:
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at bluej.runtime.ExecServer$3.run(ExecServer.java:730)
You have to rethink the loop condition: for (int run = 0; run<count;count++)
.
Neither run
nor count
are modified inside the loop, so it will run forever (until you try to read a record from your file and an Exception
occurs).
I think it should be something like:
int count = 0;
for (int run = 0; run<numberOfRecordsInFile; run++)
{
Record readone = (Record) objinputStream2.readObject();
System.out.print(readone);
System.out.println("");
count++;
}
System.out.println("Reading completed for all" + count + " records. ");
Your code:
for (int run = 0; run<count;count++)
needs to be:
for (int run = 0; run<count;run++)
Each time it runs, it tries to grab more lines than it can, because run will always be less than count the way you have it written.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.