Page 381 - CITS - Computer Software Application -TT
P. 381

COMPUTER SOFTWARE APPLICATION - CITS




                      while(( m = file_data.read() ) != -1) {
                          System.out.print((char)m);
                      }
                      file_data.close();
                  }

              }
           In the above code, we are trying to read the Hello.txt file and display its data or content on the screen. The
           program throws the following exceptions:

           1  The FileInputStream(File filename) constructor throws the FileNotFoundException that is checked exception.
           2  The read() method of the FileInputStream class throws the IOException.
           3  The close() method also throws the IOException.
           Output:































           How to resolve the error?
           There are basically two ways through which we can solve these errors.
           1  The exceptions occur in the main method. We can get rid from these compilation errors by declaring the
              exception in the main method using the throws We only declare the IOException, not FileNotFoundException,
              because of the child-parent relationship. The IOException class is the parent class of FileNotFoundException,
              so this exception will automatically cover by IOException. We will declare the exception in the following way:
              class Exception{

                  public static void main(String args[])  throws IOException {
                      ...
                      ...
              }
           If we compile and run the code, the errors will disappear, and we will see the data of the file.









                                                           368

                             CITS : IT&ITES - Computer Software Application - Lesson 101 - 108
   376   377   378   379   380   381   382   383   384   385   386