I/O Basics

  • As we uses print() and println() methods to display the content in text format and in console but those are not used in real world java programs as they are using frameworks like swing, The AWT which are the java Graphical User interfaces (GUI).
  • To obtain this java uses I/O system(Input/output) from java io package which is cohesive and consistent.

Streams

  • Java programs perform I/O through streams.

  • A stream is an abstraction that either produces or consumes information.

  • A stream is linked to a physical device by the Java I/O system.

  • All streams will perform same operations even if the physical devices which they linked are differ.

  • This means that an input stream can abstract many different kinds of input: from a disk file, a keyboard, or a networksocket. Likewise, an output stream may refer to the console, a disk file, or a network connection.

  • Java implements streams within class hierarchies defined in the java.io package.

Byte Streams and Character Streams

Java defines two types of Streams.

Byte streams-It provide a convenient means for handling input and output of bytes. Byte streams are used, for example, when reading or writing binary data.

Character streams-provide a convenient means for handling input and output of characters. They use Unicode so can be internationalized.

This were added in java 1.1 version but mostly byte streams are using than character streams.

The Byte Stream Classes

  • Byte streams are defined by using two class hierarchies.
  • At the top are two abstract classes: InputStream and OutputStream.
  • These abstract classes have sub classes which handles the differences among various devices, such as disk files, network connections, and even memory buffers.
  • The byte stream classes in java.io are
Stream Class Meaning
BufferedInputStream Buffered input stream.
BufferedOutputStream Buffered output stream.
ByteArrayInputStream Input stream that reads from a byte array.
ByteArrayOutputStream Output stream that writes to a byte array.
DataInputStream An input stream to read the Java standard data types using its methods.
DataOutputStream An output stream to write the Java standard data types.
FileInputStream Input stream that reads from a file.
FileOutputStream Output stream that writes to a file.
FilterInputStream Implements InputStream.
FilterOuputStream Implements OutputStream.
InputStream Abstract class that describes stream input.
OutputStream Abstract class that describes stream output.
ObjectInputStream Input stream for objects.
ObjectOutputStream Output stream for objects.
PipedInputStream Input pipe.
PipedOutputStream Output pipe.
PrintStream Output stream that contains println() and print() methods.
PushBackInputStream InputStream the supports one-byte "urgent", which returns a byte to the input stream.
SequenceInputStream InputStream that is combination of two or more input streams that will read sequentially one after the other.
  • The abstract classes InputStream and OutputStream define several key methods that the other stream classes implement.

  • The two mainly are read() and write() which reads and write the data of byte type.

  • These methods must be override by the stream classes.

The Character Stream Classes

  • 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 character stream classes in java.io are shown

StreamClass Meaning
BufferedReader Buffered input character stream.
BufferedWriter Buffered output character stream.
CharArrayReader Input stream that reads from a character array.
CharArrayWriter Output stream that writes to a character array.
FileReader Input stream that reads from a file.
FileWriter Output stream that writes to a file.
FilterReader Implements InputStream.
FilterWriter Implements OutputStream.
InputStreamReader InputStream that translates bytes to characters.
OutputStreamWriter OutputStream that translates characters to bytes.
ObjectInputStream Input stream for objects.
LineNumberReader InputStream that counts lines.
PipedReader Input pipe.
PipedWriter Output pipe.
PrintWriter Output stream that contains println() and print() methods.
PushBackReader InputStream that allows characters to be returned to the input stream.
Reader Abstract class that describes character stream input.
Writer Abstract class that describes character stream output.
StringReader InputStream that reads from a String.
StringWriter OutputStream that writes to a String.

The abstract classes Reader and Writer define several key methods that the other stream classes implement.

  • The two mainly are read() and write() which reads and write the data of byte type.

  • These methods must be override by the stream classes.

The Predefined Streams

  • All Java programs automatically import the java.lang package.
  • This package defines a class called System, which encapsulates several aspects of the run-time environment.
  • Using these methods we can get the properties associated with the System like sysdate.
  • System also contains three predefined stream variables: in, out, and err.

  • These fields are declared as public, static, and final within System. This means that they can be used by any other part of your program and without reference to a specific System object.

System.out-standard output stream which is console by default, is an object of type InputStream;.

System.in-Standard input Stream, which is from keyboard by default,is anobject of type PrintStream

System.err-the standard error stream, which also is the console by default, is an object of PrintStream.

Even though they are typically used to read and write characters from and to the console.

Reading Console Input

  • In Java,console input is accomplished by reading from System.in.

  • To obtain a character based stream that is attached to the console, wrap System.in in a BufferedReader object.

BufferedReader(Reader inputReader)

  • inputReader is the stream that is linked to the instance of BufferedReader that is being created. Reader is an abstract class.

InputStreamReader(InputStream inputStream)

  • InputStreamReader, which converts bytes to characters . This will obtain the object which is linked to System.in.

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

This will convert the byte data to character stream data.

Reading Characters

int read( ) throws IOException

  • it reads a character from the input stream and returns it as an integer value. It returns –1 when the end of the stream is encountered.
//example for reading characters from console
// Use a BufferedReader to read characters from the console.
import java.io.*;
public class ReadingCharacters 
{
 public static void main(String args[]) throws IOException
 {
 char c;
 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //to get data from console
 System.out.println("Enter characters, 'q' to quit.");

c = (char) br.read(); //reads the data from the inputstream using read() method of BufferedReader.
// read characters
 while(c != 'q')  //it will stop when we enter q
 {
System.out.println(c);
 c = (char) br.read();
  } 
 }
}

Output:

Enter characters, 'q' to quit.
abc12q
a
b
c
1
2

Reading Strings

String readLine( ) throws IOException

This method will return the String object which reads from console.

// Use a BufferedReader to read Strings from the console.
import java.io.*;
public class ReadingStrings
{
 public static void main(String args[]) throws IOException
 {
 // create a BufferedReader using System.in
 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 String str=null;;
 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"));
 }
}

Output:

Enter lines of text.

Enter 'stop' to quit.

hi

hello

world

12344

stop

Writing Console Output

  • print() and println() are the methods used to output the data to console which are defined by PrintStream the object reference of System.out.
  • PrintStream is an output stream derived from OutputStream, it also implements the low-level method write( ).

void write(int byteval)

  • byteval is declared as an integer, only the low-order eight bits are written.
// Demonstrate System.out.write().
public class WriteDemo {
 public static void main(String args[]) {
 int b;
 b = 'A';
 System.out.write(b);
 System.out.write('\n');
 }
}

Output:

A

The PrintWriter Class

  • PrintWriter is one of the character-based classes. Using a character-based class for console output makes internationalizing our program easier.

PrintWriter(OutputStream outputStream, boolean flushingOn)

  • outputStream is an object of type OutputStream.

  • flushing On controls whether Java flushes the output stream every time a println( )method (among others) is called.

  • If flushingOn is true, flushing automatically takes place. If false, flushing is not automatic.

// Demonstrate PrintWriter
import java.io.*;
public 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 = 4.5e-7;
 pw.println(d);
 }
}

Output:

This is a string

-7

4.5E-7

results matching ""

    No results matching ""