Processing and exclusions of java files

The standard way to handle reading and writing files in java is something like this:

try { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("file.dat")); oos.writeObject(h); oos.close(); } catch (FileNotFoundException ex) { } catch (IOException ex) { } 

But this bothers me, because here it is possible that the file never closes if an exception is thrown. Of course, we could add a finally clause and initialize an ObjectOutputStream outside the try block. However, when you do this, you need to add another try / catch INSIDE block, finally a block ... it's just ugly. Is there a better way to solve this problem?

+4
source share
5 answers

use apache commons io

http://commons.apache.org/proper/commons-io/

look at your FileUtils class. Full of gold. Gold, I say ....

+8
source

This is not a standard way. This is a bad way.

I use most of the time:

 ObjectOutputStream out = null; try { out = new ObjectOutputStream(new FileOutputStream("file.dat")); // use out } finally { if (out != null) { try { out.close(); } catch (IOException e) { // nothing to do here except log the exception } } } 

The code in the finally block can be placed in a helper method, or you can use commons IO to silently close the stream, as indicated in other answers.

In the final block, the stream should always be closed.

Note that JDK7 will greatly simplify the new syntax that will automatically close the stream at the end of the try block:

 try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("file.dat"))) { // use out } 
+6
source

This is why I use commons-io IOUtils.closeQuitely (...)

 try { ... } finally { IOUtils.closeQuietly(costream); } 
+3
source
 try { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("file.dat")); oos.writeObject(h); //oos.close(); // glow coder removed } catch (FileNotFoundException ex) { } catch (IOException ex) { } // glowcoder adds: finally { try { oos.close(); } catch(IOException ex) { // dammit we tried! } } 
0
source

add this definitively:

 finally{ if(oos != null) oos.close(); } 
0
source

Source: https://habr.com/ru/post/1341371/


All Articles