Java
  Home arrow Java arrow Page 2 - Java Part 5: Input And Output Operations
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVA

Java Part 5: Input And Output Operations
By: Chris Noack
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 3 stars3 stars3 stars3 stars3 stars / 23
    2002-01-03

    Table of Contents:
  • Java Part 5: Input And Output Operations
  • Our file I/O application explained
  • Our file I/O application explained (contd.)
  • Conclusion

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Java Part 5: Input And Output Operations - Our file I/O application explained


    (Page 2 of 4 )

    Our application will accept the name of a file from the command line. Using Java's built in I/O classes, we will then open that file for reading, outputting each line to the screen until we reach the end of the file. Some basic error handling will also be included in our sample I/O application.

    Our Java application will be created in a file named "FileIO.java". The complete source code for "FileIO.java" looks like this:

    public class FileIO{



    public static void main( String[] args ){

    try{

    try{

    String fileName = args[0];



    FileReader fr = new FileReader(fileName);

    BufferedReader input = new BufferedReader(fr);



    String s = input.readLine();

    while( s instanceof String ){

    System.out.println(s);

    s = input.readLine();

    }

    }

    catch(ArrayIndexOutOfBoundsException e){

    System.out.println("No Input File\n\nFileIO usage: java FileIO <filename>");

    System.exit(1);

    }

    }

    catch( IOException e){

    System.out.println("FileNotFound");

    System.exit(1);

    }

    System.exit(0);

    }

    }


    Allow me to describe this code for you.

    import java.io.*;

    Our application starts with an "import" reference to the "java.io.*" libraries. In Java, a library is simply a collection of classes, each of which can be instantiated from within our application.

    The "import" keyword is very similar to C and C++'s "include" directive. The "java.io" library provides system input and output through data streams, serialization and the file system. The "*" at the end of the import statement tells the Java compiler that we would like to have all of the classes declared in the "java.io" library available for instantiation from within our application. There are many other class libraries available to us from within Java. You can view a complete list of these here: http://java.sun.com/products/jdk/1.2/docs/api/.

    To keep it simple, our application isn't designed with code-reuse or portability in mind. It simply contains a class named "FileIO", which contains a "main" method. This "main" method is the applications entry point and contains the code for our entire application.

    public class FileIO{

    public static void main( String[] args ){


    As you can see, the "main" method is static, meaning that it isn't referred to from any instances of that class. It accepts an array of string arguments, which are automatically created by the Java compiler from any extra characters that are entered at the command line, after our applications filename has been typed.

    If we ran our application once it was compiled using this line, for example:

    java FileIO textfile.txt –second /third

    … then the "args" argument would contain an array of three strings (starting at an index of zero): "textfile.txt", "-second", and "/third". Each space after the actual filename is considered a separator, and creates a new string variable in the "args" array.

    try{

    // First try blocks code goes here

    try{

    // Second try blocks code goes here

    }

    catch(ArrayIndexOutOfBoundsException e){

    System.out.println("No Input File\n\nFileIO usage: java FileIO <filename>");

    System.exit(1);

    }

    }

    catch( IOException e){

    System.out.println("File Not Found");

    System.exit(1);

    }


    Two "try...catch" blocks make up the bulk of our "main" method. The "try" block allows us to tell the Java compiler to execute any code between its set of braces. If the code between the "try" braces produces an error, then Java automatically re-directs program execution to its corresponding "catch" block. All errors are handled manually from within the "catch" block, instead of having the compiler spit the error out to the screen.

    A "catch" block accepts only one argument, which is the exception object that is automatically thrown by Java. This allows us to setup our application so that it catches only certain errors from within its corresponding "try" block. If any error occurs that does not match the type of error we have specified, then our application would halt, spitting that error to the screen.

    For example, if the first "try" block throws an "ArrayIndexOutOfBoundsException" exception (meaning that we have tried to access an invalid index within an array), then it's caught and we tell the user that they haven't entered a file name.

    Likewise, if the second "try" block throws an "IOException" error, then something went wrong when trying to open the file, and we output "File Not Found" to the screen.

    Using the "try...catch" block error-handling method gives us a great amount of control over our code, and is similar to using Visual Basics "On Error Goto myError" statement, and PHP's "@" symbol.

    More Java Articles
    More By Chris Noack


     

    JAVA ARTICLES

    - Deploying Multiple Java Applets as One
    - Deploying Java Applets
    - Understanding Deployment Frameworks
    - Database Programming in Java Using JDBC
    - Extension Interfaces and SAX
    - Entities, Handlers and SAX
    - Advanced SAX
    - Conversions and Java Print Streams
    - Formatters and Java Print Streams
    - Java Print Streams
    - Wildcards, Arrays, and Generics in Java
    - Wildcards and Generic Methods in Java
    - Finishing the Project: Java Web Development ...
    - Generics and Limitations in Java
    - Getting Started with Java Web Development in...






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway
    Stay green...Green IT