How I may help
LinkedIn Profile Email me!
Call me using Skype client on your machine

Reload this page I/O Programming

This page summarizes how Java and other computer languages accept and send data to system files.

The java.io packageA website external to this site reads and writes data to flat files. Class names containing the word “stream,”, such as the FileInputStream class, perform byte by byte I/O Class names containing the word “reader” or “writer”, such as the FileReader class, perform character by character I/O.

 

Topics this page:

  • IO What?
  • File I/O
  • Stream I/O
  • Console Buffered IO
  • File Output
  • Sockets
  • Externalizable Versioning
  • Your comments???

  •  

    Site Map List all pages on this site 
    About this site About this site 
    Go to first topic Go to Bottom of this page


    Set screen Input/Output What?

      "Bridge, 2003" (Watercolor) by Sean Scully
      Different i/o classes are needed to accomodate the different ways data is formatted, manipulated, and presented.

      The java.io.InputStream and java.io.OutputStream classes and their subclasses handle 8 -bit ISO-Latin-1 (ASCII) bytes (data type "byte").

      The java.io.Reader and java.io.Writer classes and their subclasses handle streams of 16-bit Unicode characters (data type "char") needed for internationalized applications.

      Character streams use buffering techniques internally, so they potentially work faster than byte streams.

      The java.io.InputStreamReader and java.io.OutputStreamWriter classes bridge the gap between the byte and character stream classes.

      Java also provides i/o classes to recognize different file formats and protocols:

      • FileReader and FileWriter for reading from or writing to files
      • CheckedInputStream and CheckedOutputStream for reading/writing and maintaining a checksum for verifying the integrity of the data.
      • GZIPInputStream and GZIPOutputStream for reading/writing data using GZIP compression/decompression scheme.
      • ZipInputStream and ZipOutputStream for reading/writing ZIP archive files.
      • CryptoInputStream and CryptoOutputStream for encrypting and decrypting files.
      • ObjectInputStream and ObjectOutputStream for object serialization such as XML
      • PipedReader and PipedWriter Used to forward the output of one thread as the input to another thread
      • StringReader and StringWriter For reading from or writing to strings in memory

     
    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen File Input/Output

      tool The Rioja java i/o class library from IBM Alphaworks enables Java applications, on any Java platform, to sequentially scan, append, overwrite, and update binary records in record-oriented (not byte-stream oriented) files, It can list, create, rename, and delete files in multiple file systems. Rioja also maintains indexes to support keyed access to record-oriented files.

      Typically, only the persistence layer should interact with databases. Persistence is the mechanism by which objects are saved and restored between program executions (typically to a database).


    Go to Top of this page.
    Previous topic this page
    Next topic this page

      Set screen Windows File System Object Methods

      This code instantiates objects from the Microsoft Windows FileSystemObject object model under the Scripting type library in the Scrrun.dll file within the appropriate system directory on the Web server:

        [VBScript]
        Dim fso
        Set fso = CreateObject("Scripting.FileSystemObject")
        

        [JScript] var fso; fso = new ActiveXObject("Scripting.FileSystemObject");

      Note that only one instance of the FileSystemObject object is created, regardless of how many times this code is executed.

    Task ActiveX Method Java method
    Find out the path of system folders. FileSystemObject.GetSpecialFolder -
    Get an instance of an existing Folder object. FileSystemObject.GetFolder -
    Find out if a folder exists on a drive. FileSystemObject.FolderExists boolean canRead()
    boolean canWrite()
    Get the name of a folder's parent folder. FileSystemObject.GetParentFolderName -
    Retrieve the name of a folder. Folder.Name -
    Retrieve the length of a file. - long length()
    Create a folder. FileSystemObject.CreateFolder boolean mkdir()
    Delete a folder. Folder.Delete or FileSystemObject.DeleteFolder boolean delete()
    Move a folder. Folder.Move or FileSystemObject.MoveFolder -
    Copy a folder. Folder.Copy or FileSystemObject.CopyFolder -
    Rename a file - boolean renameTo(File newname)
    Note: the FSO object model doesn't support the creation or deletion of drives.


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Stream Input/Output

      MS dot NET Streams

      Disk input > FileStream > Memory Stream > Compression Stream > Crypto Stream > output

        using System;
        using System.IO;
        
        class Class1
        {
            static void Main()
            {
                using (TextWriter w = File.CreateText("out.txt");
                {
                     w.WriteLine ("Log: <{0}> {1:MM.dd.yy HH:MM}",
                          Environment.UserName, DateTime.Now);
                }
                using (TextReader r = File.OpenText ("out.txt");
                {
                     Console.WriteLine ( r.ReadLine() );
                }
            }
        }

      Java Streams

      This sample coding uses the FileInputStream and FileOutputStream classes from the java.io package A website external to this site to read data from a user-specified file to a buffer, and then out to standard output and a user-specified file.

      import java.io.*;
      public class myFileStreamsExample {
      	public static void main (String args[]) 
      		throws IOException {
      	File myFile = new File(args[0]);
      	File newFile = new File(args[1]);
      	System.out.println();
      	if(myFile.exists()) {
      		System.out.println(args[0] + " exists!\n");
      		FileInputStream inputFile = new FileInputStream(myFile);
      		// Copy entire input file to a buffer:
      		int bytesAvailable = inputFile.available();
      		byte[] buffer = new byte[bytesAvailable];
      		int bytes = inputFile.read(buffer);
      
      		System.out.println("Copying contents to " + args[1]);
      		FileOutputStream outputFile = new FileOutputStream(newFile);
      		outputFile.write(buffer);  // writes entire file from buffer.
      		outputFile.close();
      
      		// Write input file to Standard System.Output once:
      		System.out.println("inputFile named " + args[0] + " has " +
      			bytesAvailable + " bytes in file" );
      		while(bytes != -1) {
      			System.out.write(buffer, 0, bytes);  // 0 = offset
      			bytes = inputFile.read(buffer);
      		}
      		inputFile.close();
      	} else {
      		System.out.println(args[0] + " does not exist\n");
      	}
      	System.out.println();
      	}
      }
      

      The file input methods:

      • available() - returns an int. This value is the number of bytes that can be read from the FileInputStream object without
      • close() - doesn't return anything. When the method is called, the FileInputStream object is closed, and all system resources associated with the stream are released.
      • read() - returns an int that is the byte read from the file. This method will only read one byte at a time. When the end of the file is reached, a -1 is returned.
      • read(byte[] buffer) - returns an int representing the number of bytes read into the buffer. When the end of the file is reached, a -1 is returned. This method will read data from the FileInputStream object and store it in an array of bytes which is specified as a parameter. It will continue reading until the end of the file, or until the array is full.
      • read(byte[] buffer, int offset, int length) - works very similarly to the previous read method, except that you can specify the number of bytes to read (with the length parameter) and where in the FileInputStream object to start (with the offset parameter). When the end of the file is reached, a -1 is returned.
      • skip(long bytes) - returns a long value representing the number of bytes that were actually skipped. When you call this method, you must specify, via the parameter, how many bytes you want to skip over before you start reading in the file.

      Blocking occurs when there is no data available for a method to read. It forces the thread in which the method is running to pause and wait for data to become available. In multi-threaded programs, this isn't much to be concerned about, but you can see where it would be a problem in a program with only one thread.

      Exceptions

      IOException is a generic I/O exception—the father of all java.io package exceptions.

      Others:

      • EOFException - End of File or Stream has been reached.
      • FileNotFoundException - No such File exists.
      • InterruptedIOException - The I/O operation has been interrupted.
      • IOException - A generic I/O exception has occurred, the father of all java.io package exceptions.
      • NotSerializableException - An attempt has been made to read/write an object that can not be sent to a file or socket. (This is explained further in the following section.)


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Basic File Output

      Stream Methods:
      • write(byte[] b) - doesn't return anything. This method takes an array of bytes as a parameter, and writes that array to the FileOutputStream object.
      • write(byte[] b, int offset, int length) - functions much like the previous write method. This method gives you the ability to say where to start pulling information from in the byte array (offset) and what how much information to pull from the byte array (length). Both the offset and length parameters specify a number of bytes.
      • write(int byte) - returns nothing. This method can only write one byte to the FileOutputStream object at a time which is specified by the parameter byte.
      • close() - doesn't return anything. When the method is called, the FileOutputStream object is closed, and all system resources associated with the stream are released.

      Example:

      gos.write('a');

      This can be the method of the outermost class if the source for the stream is chained by code such as this:

      FileOutputStream fos = new FileOutputStream("myfile.out");
      CryptOutputStream cos = new CryptOutputStream(fos);
      GZIPOutputStream gos = new GZIPOutputStream(cos);

      or simply:

      GZIPOutputStream gos = new GZIPOutputStream(new CryptOutputStream(new FileOutputStream("myfile.out")));


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Console Buffered IO

      To read and write to the command prompt console:

      import java.io.*;

      public class ReadStringFromConsole {

        public static void main (String[] args) {
          System.out.print("Prompt: ");
          BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
          String strInput = null;
          try {
            strInput = br.readLine();
          } catch (IOException ioe) {
            System.out.println("Error trying to read input.");
            System.exit(1);
          }
          System.out.println("Thank you, " + strInput );
        } // end of main.
      } // end of ReadStringFromConsole class


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Resources


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Java Serializable Sockets Programming

      To save an Object to a File or send an Object through a network Socket, that Object's class must implement the java.io.Serializable InterfaceA website external to this site.

      The Serializable Interface has no fields or methods; it serves to inform the compiler about the desire to store/transmit objects of this class.

      When a class extends a non-serializable class, the fields inherited from the superclass will not be stored or transmitted.

      Fields marked with modifier key word transient are not stored or transmitted.

      Class in java.net Exception
      URL MalformedURLException - a bad Internet address UnknownHostException - cannot find the host
      DataGramPacket (a low-level form of networking) SocketException - an error in the attempt to communicate
      Socket BindException - failure to connect to a Socket
      ServerSocket

      PORTS: There are a number of pre-assigned ports. If your Java program attempts to start a server at a port already in use, you will get a BindException. Generally ports under 1024 require administrator permission. Most general purpose Java Servers will listen at port 5000 or greater. The maximum port number allowed currently by TCP/IP is 32767.


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Externalizable Versioning

      Java provides the java.io.Externalizable Interface to support versioning. This interface requires the class to write its own Object I/O routines, thus controlling what is read and what is written.


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Portions ©Copyright 1996-2010 Wilson Mar. All rights reserved. | Privacy Policy |

    Related topics:

  • Databases
  • Java Architecture
  • Data Types, Strings, Escape Characters, Dates
  • Programming Logic, Operators, Functions, Threads, AWT/Swing
  • Applications Development
  • On the web

  • How I may help

    Send a message with your email client program


    Your rating of this page:
    Low High




    Your first name:

    Your family name:

    Your location (city, country):

    Your Email address: 



      Top of Page Go to top of page

    Thank you!