Khurram's World - JAVA Input / Output Package
 
 
..Islam and Religion
 .Computer & IT
  Web Designing TIPS
..HTML & DHTML
..Active Server Pages
..JAVA & JAVA Applets
..JAVA & VB Script
..CGI & Perl
..Electronic Commerce
..Web Sites & Emails
 
Pakistan News Service
Bay Banner
 
 
 
java.awt.package  

Objective

Objective:

        Learn about:
        Using JAVA for DATA transfer
        Concept of Streams and Files

Reading and writing Streams and Files

 

Concept:

Streams

JAVA programs perform input and output through streams. A stream is either a source or destination for the data or information. A stream in linked to a physical device by the JAVA I/O stream. All streams in the same manner, even if the actual physical devices to which they are linked differ. So the same I/O classes and methods can be applied to perform I/O from any type of device. Streams are the clean way to deal with input / output. JAVA implements streams within class hierarchies defined in the java.io package.

When you write data to a stream it is called Output Stream and when you read data from a stream it will called Input Stream.

 

JAVA – 2 defines two types of streams;

Byte Streams

Character Streams

 

Byte Streams

Byte streams provide easy way for handling input and output of Bytes. These are used while reading and writing binary data. When you write data to a stream as a series of bytes, it is written to the stream exactly as it appears in memory. No transformation of data takes place. No transformation of data takes place.

Byte streams are defined by using two class hierarchies. At the top are two abstract classes: InputStream and OutputStream. Each of these abstract classes has a number of concrete subclasses that handle various different devices, such as disk, files, network connections and even memory buffers.

The abstract classes InputStream and OutputStream define several key methods that the other stream classes implement. Two of the most important are read() and write(), which read and write bytes of data. Both methods are declared as abstract inside InputStream and OutputStream. They are overridden by derived stream classes.

 

Character Streams

Character streams are used for storing and retrieving text from a location or file by a JAVA program. All numeric data is converted to textual from before being written to the stream. Reading numeric data from the stream of characters involves much more work than reading binary data.

Stream input and output methods generally permit very small amount of data such as byte or char to be written and read in a single operation. Sending data transfer like this would be extremely inefficient, so stream is often equipped with a buffer, which is called Buffered Stream.

Character streams are defined by using two class hierarchies. At the top are two abstract classes: Reader and Writer. These abstract classes handle Unicode character streams. JAVA has several concrete subclasses of each of these. 

The abstract classes Reader and Writer define several key methods that the other stream classes implement. Two of the most important are read() and write(), which read and write characters of data. Both methods are declared as abstract inside Reader and Writer. They are overridden by derived stream classes.

 

Buffered Streams

Buffered streams ensure that data transfer between memory and external device are in large chunks to make this process efficient. A buffer is simply a block of memory that is used to batch up a data transfer. When you write to a buffered stream the data is sent to buffer (not to external device). The amount of data in the buffer is tracked automatically, and the data is sent to the device when the buffer is full. You can do it manually by flushing the buffer.

 

The Predefined Streams

All JAVA programs automatically import the java.lang package. This package defines a class called System. It contains several methods that can be used to obtain the current time and the settings of various properties associated with the system. System also contains three predefined stream variables, in, out and err. These fields are declared as public and static within System. This means that they can be used by any other part of the program without reference to a specific System object.

System.out referes to the standard output stream. By default, this is the console. System.in refers to the standard input, which is keyboard by default. System.err refers to the standard error stream, which is also console by default. However, these streams may be redirected to any compatible I/O device.

System.in is an object of type InputStream; System.out and System.err are objects of type PrintStream. These are byte streams, even though they typically are used to read and write characters from and to the console.

 

Reading Console Input

In JAVA 1.0, the only way to perform console input was to use a byte stream, but the preferred method of reading console input for JAVA 2 is to use a character oriented stream, which makes a program easier to internationalize and maintain.

In JAVA, console input is accomplished by reading from System.in. To obtain a character-based stream that is attached to the console, you wrap System.in in a BufferedReader object, to create a character stream. BufferedReader supports a buffered input stream. Its most commonly used constructor is:

BufferedReader (Reader inputReader)

Here, input reader is the stream that is linked to the instance of BufferedReader that is being created. Reader is an abstract class. One of its concrete classes is InputStreamReader, which converts bytes to characters. To obtain an InputStreamReader object that is linked to System.in, use the following constructor:

 

BufferedReader (InputStream inputstream)

 

Because, System.in refers to an object of type InputStream, it can be used for inputStream. Putting it all together, the following lines of code create a BufferedReader that is connected to the keyboard.

 

BufferedReader br = new BufferedReader (new InputStreamReader(System.in);

 

After this statement executes, br is character-based stream that is linked to the console through System.in.

 

Reading Strings

To read a string from the keyboard, use the method readLine() that is a member of the BufferedReader class. Its general form is shown here:

 

String readLine() throws IOException

 

This returns a String object. The following program demonstrates BufferedReader and the readLine() method; the program reads and displays lines of text until you enter the word “stop”:

 

//Read a string from console using a BufferedReader.

Import java.io.*;

class BRReadLines {

        public static void main (String args[]) throws IOException {

                //create a BufferedReader using System.in

                BufferedReader br = new BufferedReader (newInputStreamReader(System.in);

                String str;

                System.out.println(“Enter lines of text.”);

                System.out.println(“Enter ‘stop’ to quit.”);

                do {

                        str = br.readLine();

                        System.out.println(str);

                        } while (!str.equals(“stop”));

                }

 

}

 

Writing Console Output

Console output is most easily accomplished with print() and println(). These methods are defined in the class PrintSream (which is the type of object referenced by System.out). System.out is a byte stream. For character-based output, PrintStream is used which is derived from OutputStream. It implements a methods write() to write to the console. The simplest form of write() defined by PrintStream is:

void write (int byteval) throws IOException

this method writes to the file the byte specified by byteval. Here is a short program that uses write() to output the character “A” followed by a newline to the screen:

//Demonstrates System.out.write()

class WriteDemo {

        public static void main(String args[]) {

                int b;

                b = ‘A’;

                System.out.write(b);

                System.out.write(‘\n’);

        }

}

 

The PrintWriter Class

System.out is recommended mostly for debugging purposes or for sample programs. For real-world program, the recommended method of writing to the console using JAVA is through a PrintWriter stream. PrintWriter is one of character-based streams. Using a character-based class for console output makes it easier to internationalize your program

PrintWriter (OutputStream outputstream, Boolean flushOnNewline)

Here, outputStream is an object of type OutputStream, and flushOnNewline control whether JAVA flushes the output stream every time a newline (‘\n’) character is output. If flushOnNewline is true, flushing automatically takes place. If false, flushing is not automatic.

PrintWriter supports the print() methods for all types including Object. This, you can use these methods in the same way as they have been used with System.out. if an argument is not a simple type, the PrintWriter methods call the object’s toString() method and then prints the result.

To write to the console using PrintWriter, specify System.out for the output stream and flush the stream after each newline. For example, this line of code creates a PrintWriter that is connected to the console output:

 

Printwriter pw = new PrintWriter(System.out, true);

 

The following program illustrates using a PrintWriter to handle console output:

//Demonstrates PrintWriter

import java.io.*;

class PrintWriterDemo {

        public static void main (String args[] {

                PrintWriter pw = new PrintWriter (System.out, true);

                Pw.println(“This is a string”)

                int i = -7;

                pw.println(i);

                double d = 1.5e-7;

                pw.println(d);

        }

}

 

File Class

Although most of the classes defined by java.io operate on streams, the File class does not. It deals directly with files and the file system. That is, the File class does not specify how information is retrieved from or stored in files; it describes the properties of a file itself. A file object is used to obtain or manipulate the information associated with a disk file, such as the permission, time, date, and the directory path, and to navigate subdirectory hierarchies.

Files are a primary source and destination for data within many programs. Although there are severe restrictions on their use within applets for security reasons, files are still a central source for storing persistent and shared information. A directory in JAVA is treated simply as a File with one additional property – a list of filenames that can be examined by the list() method.

A file object represents a pathname of a physical file on your hard disk, not a stream. File class also provides methods to test the objects you create. File class has three constructors:

1)     File (String dirpath);

This creates a new File object by converting the given pathname string into an abstract pathname, e.g. File myDir = new File (“c:\Khurram\OEC”);

 

You can also write:

File myDir = new File (“c:\Khurram\OEC\file.txt”);

 

2)     File (String dirObject, String filename);

This creates a new file object from a parent abstract pathname and a child file name string, e.g.

File myFile = new File (myDir, “File.txt”);

File (String dirpath, String filename);

The third constructor is the same as the 2nd but it accepts String Object identifying the directory rather than file object. The second object is still a String object referring to file name, e.g.

The following methods can check file objects:

exists() isDirectory() isFile() isHidden()
isAbsolute() canRead() canWrite() equals()
renameTo(filepath) delete() CreateNewFile() mkdir()

 

Example:

import java.io.*;

public class TryFile {

        public static void main(String args[]) {

                boolean ch;

                File myDir = new File (“D:\work”);

                if (myDir.isDirectory())

                        System.out.println(“Directory exists”);

                else {

                        System.out.println(“Directory does not exists”);

                ch = myDir.mkDir();

                if (ch) {

                        System.out.println(“Directory created”); }

                        }

 

                File myFile = new File (myDir, “File.txt”);

                if (myfile.exists())

                        System.out.println(“File Exists”);

                else {

                        System.out.println(“File does not exists”);

                try {

                        ch = myfile.createNewFile();

                        if (ch) {

                                System.out.println(“File Successfully created”);

                        }

                } catch (Exception e) {

                        e.printstachTrace();

                        }

                }

        }

}

 

FileReader

The FileReader class creates a Reader that you can use to read the contents of a file. Its two most commonly uses constructors are shown here:

FileReader (String filePath)

FileReader (File fileObj)