1
votes

I'm studying for OCP exam these classes I/O:

  • OutputStream subclasses:

    • FileOutputStream
    • BufferedOutputStream
    • DataOutputStream
    • PrintStream (I see its methods write() don't throw exceptions)
  • Writer subclasses:

    • FileWriter
    • BufferedWriter
    • PrintWriter (I see its methods write() don't throw exceptions)
  • Reader subclasses:

    • FileReader
    • BufferedReader
  • InputStream subclasses:

    • BufferedInputStream
    • FilterInputStream
    • ObjectInputStream

My question: For the main methods read and write (with different signatures), when does each of these classes throw the IOException? In the javadoc there is only a phrase:

IOException - if an I/O error occurs

without an explanation about the cases.

I know this (I don't know if these are correct):

  • FileOutputStream throws java.io.FileNotFoundException if the file doesn't exist. This class, infact, doesn't create a file;

  • FileWriter throws java.io.FileNotFoundException if the file doesn't exist. This class infact, doesn't create a file;

  • BufferedReader throws java.nio.file.NoSuchFileException (subclass of IOException), if file doesn't exist;

  • FileInputStream throws java.io.FileNotFoundException if the file doesn't exist.

Thanks a lot!

A.

2
Creating a FileWriter/OutputStream does create the file. It's vague on purpose: any IO problem will cause an IOException to be thrown. For example, if the file is being deleted while reading/writing. Or if the hard drive is damaged. Or if there is no space left to write, or the OS somehow refuses to read or write (because there is a network error on a network drive, or because there is a permission issue). It could be a lot of things. - JB Nizet

2 Answers

1
votes

If you google the API documentation for the class, generally the Javadocs will give an explanation of what exceptions are thrown in what circumstances, e.g. for FileWriter

https://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html

1
votes

An I/O exception is thrown by any of these classes when they encounter a problem during execution. The file output streams can throw an exception if :

  • File don't exist
  • File is read only
  • The OS refuses access to the file
  • The drive you are writing to dose not have sufficient space

The input streams usually throws exception if :

  • The stream is not properly initialised
  • The input type is miss matched
  • If the file beeing read from is changed while reading
  • If the file doesn't exist.