Home

      Hosting      Domains       Support       Contacts

Java Tutorial Home 2 3 4 5 6 7 8 9

Java IO Framework



System.in Object
-  Wrapping in a hierarchy just to read input from the user.
-  Whatever the users types the return type will always be a string because of the wrapping.
 
java.io package
-  Reader, streams and buffers and readers.
-  You can read and write objects but only if they were read and written as objects in the first place. Hierarchy for Output Classes
-  Writer, streams buffers and output streams.
 
Reading from the Java Console.
-  Scanner class encapsulates all this reading and writing.
 
Alternative coding

BufferedReader br = new BufferedReader
-  can readline and close  Java closes when the program terminates but you should always close  the file.
 
Hiding the Complexity
-  Create a class to hide the complexity do this for reading.
 
Reading Text Files

import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileNotFoundException;
 
public class ReadTextFiles
{
  public static void main( String [] args )
  {
    try
    {
       FileReader fro = new FileReader( "myFile.txt" );
       BufferedReader bro = new BufferedReader( fro );
 
       // declare String variable and prime the read
       String stringRead = bro.readLine( );
 
       while( stringFromFile != null ) // end of the file
       {
          System.out.println(stringFromFile);
          stringFromFile = bro.readLine( );  // read next line
       }
 
       bro.close( );
    }
 
    catch( FileNotFoundException filenotfoundexxption )
    {
      System.out.println( "myFile.txt, does not exist" );
    }
 
    catch( IOException ioexception )
    {
      ioexception.printStackTrace( );
    }
  }
}

 
myFile.txt is on the same drive in directory where you are compiling, needs to be in a try to catch FileNotFound exception and IOError.  Which throws the exception, the FileReader throws the FileNotfound because of the FileReader constructor
 
Constructors for Writing text files
-  Writing over and append.  Mode for these if the mode is true is append. What happens if the file does not exist and the mode is true?  File is created.
-  BufferedWriter uses a write, newline, and close methods.
 
Example
 

import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
 
public class WriteTextFiles
{
  public static void main( String [] args )
  {
    try
    {
       FileWriter fwo = new FileWriter( "output.txt", false );
       // false means we will be writing to the file
       BufferedWriter bwo = new BufferedWriter( fwo );
 
       // write four lines
       bwo.write( "I never saw a purple cow," );
       bwo.newLine( );
       bwo.write( "I never hope to see one;" );
       bwo.newLine( );
       bwo.write( "But I can tell you, anyhow," );
       bwo.newLine( );
       bwo.write( "I'd rather see than be one!" );
       bwo.newLine( );
 
       // release resources associated with output.txt
       bwo.close( );
       System.out.println( "all OK" );
    }
 
    catch( IOException ioexception )
    {
      ioexception.printStackTrace( );
    }
  }
}

 
 
Reading structure records
 
Example
-  Airline example.  Sometimes you want to read Comma separated values(CSV) files into a record to structure the information.  We can parse these values or "tokens" in a file to put it into a record using the String Tokenizer Class (StringTokenizer).
 
StringTokenizer Methods
-  countTokens (unretrieved tokens, i.e. the number left not total)
-  nextToken gives you the next token and the token gets removed.
 
Using StringTokenizer
-  import from java.util.StringTokenizer
-  You can vary the delimiter.
 


import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.StringTokenizer;
import java.util.ArrayList;
 
public class ReadFlights
{
  public static void main( String [] args )
  {
   // declare ArrayList to hold FlightRecord objects
   ArrayList<FlightRecord> listFlightRecords =
                      new ArrayList<FlightRecord>( );
 
   try
   {
     FileReader fr = new FileReader( "flights.txt" );
     BufferedReader br = new BufferedReader( fr );
 
     // declare String variable and prime the read
     String stringRead = br.readLine( );
 
     while( stringRead != null ) // end of the file?
     {
       // process the line read
       StringTokenizer st = new
              StringTokenizer( stringRead, "," );
       String flightNumber = st.nextToken( );
       String origin = st.nextToken( );
       String destination = st.nextToken( );
 
       try
       {
         int numPassengers =
                 Integer.parseInt( st.nextToken( ) );
         double avgTicketPrice =
                 Double.parseDouble( st.nextToken( ) );
 
         FlightRecord frTemp = new FlightRecord(
                                      flightNumber,
                                      origin,
                                      destination,
                                      numPassengers,
                                      avgTicketPrice );
 
         // add FlightRecord obj to listFlightRecords
         listFlightRecords.add( frTemp );
       }
 
       catch( NumberFormatException nfe )
       {
         System.out.println( "Error in flight record: "
                              + stringRead
                              + "; record ignored" );
       }
 
       // read the next line
       stringRead = br.readLine( );
     }
 
     // release resources associated with "flights.txt"
     br.close( );
   }
 
   catch( FileNotFoundException fnfe )
   {
     System.out.println( "Unable to find flights.txt" );
   }
 
   catch( IOException ioe )
   {
     ioe.printStackTrace( );
   }
 
   // print the FlightRecords read
   for ( FlightRecord flight : listFlightRecords )
       System.out.println( flight );
 }
}


 
FlightRecord class does have a constructor so the default is used. Just sets parameters for FlightRecord.  Prints pretty.
 
If you have flight record of one million records you now have an array available to use as an objects.
 
Reading and Writing Objects
-  Ability to write objects.  Rights the entire code, i.e. data fields and methods unless static or transient. Usage for doing this is not necessarily clear.  The big thing is interoperability, i.e. XML data from Windows to Unix, webservices.
 
Writing objects to a file
-  Any class to write objects as a file you have to write/implement Serializable.
-  There are no methods to import. Just need to import.
-  Objects need to be Serializable.
 
The ObjectOutputStream
-  Just like Write output.
 
writeObject Method
-  readObject returns an object but it doesn't know what kind of object
it is so you have to typecast it to tell it that it's your kind of object.
 
These mean execute forever:

while (true)
for (;;)
while (1=1)

 
Omitting Data from the file.
-  private transient - values that you can construct when being pulled
back to a file.
-  Fields of objects that are not serializable.

 

Java Tutorial Home 2 3 4 5 6 7 8 9


Java Tutorial


| Home | Hosting | Domains | Support |  Contacts |
|
Terms & Condition | Privacy Policy |


 

Copyright 2005 by HostItWise.com Read our Copyright. All rights reserved.

Garage Door Circle  | RushRash Inc | Home Field Realtors