Home arrow Java arrow Page 2 - Java Part 5: Input And Output Operations
JAVA

Java Part 5: Input And Output Operations


In this article, Chris will continue his popular "Java How-To" series and teach us all how to create a simple Java application that will read a file and output its contents to the screen.

Author Info:
By: Chris Noack
Rating: 3 stars3 stars3 stars3 stars3 stars / 30
January 03, 2002
TABLE OF CONTENTS:
  1. · Java Part 5: Input And Output Operations
  2. · Our file I/O application explained
  3. · Our file I/O application explained (contd.)
  4. · Conclusion

print this article
SEARCH DEVARTICLES

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.
blog comments powered by Disqus
JAVA ARTICLES

- Java Too Insecure, Says Microsoft Researcher
- Google Beats Oracle in Java Ruling
- 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 ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials