The output is correct but it's followed by an EOFException. I read the documentation but still i don't know how to solve this
try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream("file.bin"))){
for(Ser s = (Ser)ois.readObject(); s!=null; s=(Ser)ois.readObject() )
System.out.println(s);
}catch (IOException | ClassNotFoundException e){
e.printStackTrace();
}
You are assuming that readObject returns null if there is no data, but in fact it throws EOFException. The simplest fix is just to catch the exception:
try(...) {
for(;;) {
Ser s = (Ser)ois.readObject();
System.out.println(s);
}
} catch(EOFException e) {
// normal loop termination
} catch(IOException | ClassNotFoundException e){
// error
}
Be aware that some people and coding standards consider it bad practice to have an exception thrown in non-error conditions, like reaching the end of input in this case.
Related
I have read other questions similar to this but didn't help much. So I have some serialized content in a file and I am trying to read it and print it on the console, content is getting printed fine but at the end, it's showing an EOFException. Is there any way to fix my code to avoid this exception?
try {
File file = new File("EnrolledStudentsSerial.txt");
FileInputStream fi = new FileInputStream(file);
ObjectInputStream input = new ObjectInputStream(fi);
while(true) {
System.out.println(input.readObject());
}
}
catch (IOException | ClassNotFoundException e) {
System.out.println("Error: " + e);
}
I don't think you want to 'avoid' this exception.
You need to know when you come to the end of the input, and the EOFException is what is telling you you've come to the end of the input.
Rather, you want to stop treating it as an error condition, since it is not an error, it is normal and expected.
try {
… code as before …
}
catch (EOFException e) {
// end of input, nothing to do here
}
catch (IOException | ClassNotFoundException e) {
System.out.println("Error: " + e);
}
Good day,
Why in video lessons one human was not using try-catch, and, if i not be using try-catch i have an error IOException on createnewFile(), FileWriter etc.
Maybe this is easy, i from c++, its big question for me.
Thats my code:
PS. Sorry for "best english"
public static void main(String[] args) {
System.out.println("Hello World");
File file1 = new File("temp.txt");
if(!file1.exists()) {
System.out.println("Creating file...");
try
{
file1.createNewFile();
}
catch (IOException e)
{
e.printStackTrace();
}
}
try
{
FileWriter fw = new FileWriter(file1);
BufferedWriter out = new BufferedWriter(fw);
out.write("aString");
out.flush();
out.close();
FileReader fr = new FileReader(file1);
BufferedReader in = new BufferedReader(fr);
while(in.ready()) {
System.out.println(in.readLine());
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
We use try- catch block to maintain the flow of execution of code.
If exception occurs it goes to catch block and e.printStackTrace it gives us the information why exception occurs and we can handle it here with our logic.
if we dont use try-catch the flow of code is stuck where exception occurs.
So thats why we use try-catch block.
Java requires that you handle checked exceptions in your code, either by specifying that your method can throw the exception or by handling it with a try-catch block. If you don't do one of these two at the point where you call a method that may throw a checked exception such as IOException, the compiler is going to produce an error.
You can learn about exceptions in Java here: Lesson: Exceptions (Oracle Java Tutorials).
Specifically: The Catch or Specify Requirement
I'm writing a small program for an assignment and part of it involves reading from a file using ObjectInputStream. I've run into a brick wall because I keep getting errors when trying to close the file in the finally block as well as a NullPointerException but I cannot understand why. Any help is much appreciated! I have checked already and the file path is correct, so it is able to find the file.
Example file:
hello || apples, acai berry, bananas || shopping || 0.0005 || yes
public Disease[] readInCancers() {
Disease[] cancerList = null;
try {
FileInputStream fis = new FileInputStream(myData);
BufferedInputStream bis = new BufferedInputStream(fis);
ois = new ObjectInputStream(bis);
while(true) {
Disease disease = null;
try {
disease = (Disease)ois.readObject();
} catch (EOFException eofx) {
break;
}
if (cancerList == null || cancerList.length == 0) {
cancerList = new Disease[1];
cancerList[0] = disease;
} else {
Disease[] newList = new Disease[cancerList.length + 1];
System.arraycopy(cancerList, 0, newList, 0, cancerList.length);
newList[cancerList.length] = disease;
cancerList = newList;
}
}
} catch (FileNotFoundException fnfx) {
JOptionPane.showMessageDialog(null, "File could not be found");
} catch (IOException iox) {
JOptionPane.showMessageDialog(null, "Problem with reading from file");
} catch (ClassNotFoundException cnfx) {
JOptionPane.showMessageDialog(null, "Class could not be found");
} catch (NullPointerException npx) {
System.out.println("blah");
} finally {
try {
ois.close();
} catch (IOException iox) {
JOptionPane.showMessageDialog(null, "Problem with closing file");
}
}
return cancerList;
}
When I run the program, it gives a NullPointerException at ois.close() as well as an IOException that produces the pop-up "Problem with reading from file".
I have also tried changing how the file itself is structured, replaced the || (delimiters) with a word or even blank space but nothing changes.
Your FileInputStream is throwing an exception (I'm guessing from incorrect file permissions, but you'll have to look into this further); this occurs before you initialize your ObjectInputStream, so ois is still null when you reach your finally block which is resulting in a null pointer exception. It's usually a good idea to precede close statements in final blocks by null pointer checks for this reason.
When using an ObjectInputStream the input data is required to be in a byte format that can be read into a serialized object, Disease in this case. If the format is not in the expected format a StreamCorruptedException will be thrown. If you are changing the text file manually, chances are that this exception is being thrown but the exact message is not displayed as you are displaying a generic Problem with reading from file message.
Displaying the stack trace will help
iox.printStackTrace();
Ensure that you are writing the objects correctly to file. Alternatively you could use a text based file, and use Printwriter to write, Scanner to read. You can use || for as a Scanner delimiter.
I have a series of different object serialized into a binary file.How can I read the file until the end?
try {
ObjectInputStream reader = new ObjectInputStream(new FileInputStream(fname));
Object obj = reader.readObject();
if (obj instanceof Azienda) {
Azienda a = (Azienda) obj;
company.put(a.getCod(), a);
} else if (obj instanceof Privato) {
Privato p = (Privato) obj;
privato.put(p.getCod(), p);
}
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
} catch (FileNotFoundException ffe) {
System.err.println("Error: the file was not found!");
} catch (IOException ioe) {
ioe.printStackTrace();
}
in this way I read only once object per read.
when I read a text file I use null
try{
while(true) {
Object obj=reader.readObject()
// do sth with object
}
}catch(EOFException e){
//we expect it so ignore
}
there is no EOF check besides the exception when you read past it for ObjectInputStream so you'll have to use the code smell called exceptions for control flow
It seems that an EOFException is thrown when there is no more object to read from the stream. Unfortunately, it's not even documented. So, I see the following solutions:
you read in a loop until you get this exception,
you make it so that you know in advance the number of objects in the stream,
you make it so that there is a marker object which marks the last object of the stream,
you serialize (and unserialize) a unique object: a List<Object> containing all the objects. This last solution, of course prevents writing the objects on the fly to the stream, and forces you to have all the objects in memory before serializing them.
ObjectInputStream does not have a concrete method for checking for end-of-file.
But every read...() method of ObjectInputStream throws an EOFException when it tries to read past the end of file. Unfortunately this is not explicitly documented for readObject(), but it is for all the other methods (readInt() etc.)
http://docs.oracle.com/javase/7/docs/api/java/io/ObjectInputStream.html
ObjectInputStream reader = null;
try {
reader = new ObjectInputStream(new FileInputStream("sth"));
Object obj = null;
while ((obj = reader.readObject()) != null) {
System.out.println(obj);
}
} catch (EOFException e) {
System.out.println("finnished reading");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (FileNotFoundException ex) {
System.err.println("Error: the file was not found!");
} catch (IOException ex) {
ex.printStackTrace();
} finally {
reader.close();
}
Hello,
In Java if a method like BufferedReader.read() says it can throw an IOException and I try to catch a FileNotFoundException and an IOException in two catch blocks, what catch blocks will be entered if the file doesn't exist?
Does it enter only the most specific or both?
The first coded catch that matches the exception will be entered.
Edited to incorporate comment from Azodius
For example:
try {
bufferedReader.read();
} catch (FileNotFoundException e) {
// FileNotFoundException handled here
} catch (IOException e) {
// Other IOExceptions handled here
}
This following code does not compile:
try {
bufferedReader.read();
} catch (IOException e) {
// All IOExceptions (and of course subclasses of IOException) handled here
} catch (FileNotFoundException e) {
// Would never enter this block, because FileNotFoundException is a IOException
}
Compiler message says:
Unreachable catch block for FileNotFoundException. It is already handled by the catch block for IOException
Only the first catch block encountered where the exception type of the catch block matches the type of the exception being thrown will be run (more specifically, the first catch block where (e instaceof <exception type>)==true will be run). None of the other catch blocks will be run.
For example
try{
BufferedReader.read();
}
catch(FileNotFoundException e){System.out.println("FileNotFoundException");}
catch(IOException e){System.out.println("IOException");}
Will print FileNotFoundException if BufferedReader.read() throws a FileNotFoundException.
Note that the following doesn't actually compile:
try{
BufferedReader.read();
}
catch(IOException e){System.out.println("IOException");}
catch(FileNotFoundException e){System.out.println("FileNotFoundException");}
because Java realizes that it is not possible for the FileNotFoundException to be caught because all FileNotFoundExceptions are also IOExceptions.
The first one which is suitable for that type of exception (and only that). So if you catch the two exception types above in the order you list them, a FileNotFoundException will be caught.
Specific exception is caught first. and it's a compile time error if generic exception is caught befor specific one.