I/O Basics

advertisement
I/O Basics
• Java does provide strong, flexible support for
I/O related to files and networks.
• Java’s console based interaction is limited since in
real time application java accepts inputs from AWT
,Swing etc.
• Java performs I/O operation through streams
• Stream is an abstraction either produces or consumes
information.
• Streams linked to a physical devices in same manner
irrespective of physical devices
• Same I/O classes and methods are used for disk
files,console,etc.
Streams
• Java defines two types of streams Byte Stream and
Character stream.
• Byte streams provide a convenient means for handling
input and output of bytes. Byte streams are used when
reading or writing binary data.
• Character streams provide a convenient
means for handling input and output of characters. They
use Unicode and, therefore, can be internationalized.
• At the lowest level, all I/O are byte-oriented. The
character-based streams simply provide a convenient
and efficient means for handling characters.
• Java implements streams within class hierarchies defined
in the java.io package.
Byte Stream
• 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 several
concrete subclasses, that handle the differences
between various 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, respectively, read and write
bytes of data.
• Both methods are declared as abstract
• inside InputStream and OutputStream.
They are overridden by derived stream classes.
Character Stream
• Character streams are defined by using two
class hierarchies. At the top are two abstract
classes, Reader and Writer.
• The abstract classes Reader and Writer
define several key methods that the other
stream classes implement.
• Two of the most important methods are read()
and write(),which read and write characters
of data, respectively. These methods are
overridden by derived stream classes.
Predefined Streams
• The java.lang package defines a class called
System, which encapsulates several aspects of
the runtime environment.
• System contains three predefined stream
variables, in,out, and err. These fields are
declared as public and static within
System.
• System.out refers to the standard output
stream. By default, this is the console.
• System.in refers to standard input, which is
the keyboard by default.
• System.err refers to the standard error
stream, which also is the console by default.
Reading Console Input
• Console input is done by System.in this is an object of
InputStream (Byte Stream)
• To obtain a character-based stream that is attached to
the console , wrap System.in in a BufferedReader
object.
• BuffereredReader supports a buffered input stream.
Its most commonly used constructor is shown here:
BufferedReader(Reader inputReader)
• inputReader is the stream that is linked to the instance
of BufferedReader that is being created.
• Reader is an abstract class.
• One of its concrete subclasses is
InputStreamReader, which converts bytes to
characters.
• To obtain an InputStreamReader object that is linked
to System.in, use the following constructor:
InputStreamReader(InputStream inputStream)
• Because System.in refers to an object of type
InputStream, it can be used for inputStream.
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
• br is a character-based stream that is linked to the
console through System.in.
Reading Characters
• The method read() is used to read a character
from a BufferedReader
• Each time that read() is called, it reads a
character from the input stream and returns it
as an integer value.
• read() returns –1 when the end of the stream
is encountered.
• read() can throw an IOException.
• To read String use br.ReadLine();
• BufferedReadApplication.java
java.io.*;
class BRRead {
public static void main(String args[])
throws IOException
{
char c;
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter 'q' to quit.");
do {
c = (char) br.read();
System.out.println(c);
} while(c != 'q');
}
}
Enter 'q' to quit.
123abcq
1
2
3
a
b
• Console output is most easily accomplished
with print( ) and println( ), described
earlier.
• These methods are defined by the class
PrintStream (which is the type of the object
referenced by System.out).
• Even though System.out is a byte stream,
using it for simple program output is still
acceptable.
• However, using a PrintWriter will make your
real-world applications easier to
internationalize.
Reading and Writing Files
• In Java, all files are byte-oriented, and Java provides
methods to read and write bytes from and to a file.
• Java wraps a byte-oriented file stream within a
character-based object.
• Two of the most often-used stream classes are
FileInputStream and FileOutputStream,
which create byte streams linked to files.
• To open a file, create an object of one of these classes,
specifying the name of the file as an argument to the
constructor.
FileInputStream(String fileName) throws
FileNotFoundException
FileOutputStream(String fileName) throws
FileNotFoundException
• To read from a file,create the object of
FileInputStream and use the method
read()
• Each time that it is called, it reads a single byte
from the file and returns the byte as an integer
value. read() returns –1 when the end of the
file is encountered.
• It can throw an IOException.
• While creating an input stream , if the file does
not exist, then FileNotFoundException is
thrown.
1. Write an application that reads and counts the
number of words ,special characters, digits
and lines of a text file.the output should be
written in to another file.
• To write in to the file create the object of
FileOutputStream
FileOutputStream fout;
fout = new
FileOutputStream(fileName, true);
• Creating file in append mode
• Ref :FileApplications.java
String Handling
• String is sequence of characters
• In java String is an immutable object
• Immutable :- Strings within objects of type String are
unchangeable means that the contents of the String
instance cannot be changed after it has been created.
• However, a variable declared as a String reference can
be changed to point at some other String object at any
time.
• For those cases in which a modifiable string is
desired, there is a companion class to String called
StringBuffer, whose objects contain
strings that can be modified after they are created.
String constructors
• Following default constructor creates an instance of string with
no character in it.
String s = new String();
• To create a String initialized by an array of characters, use the
constructor shown here:
String(char chars[])
char chars[]={'a','b','c'};
String s =new String(chars);
• Specify a subrange of a character array as an initializer
using the following constructor:
String(char chars[],int startIndex,int numChars)
– startIndex specifies the index at which the subrange
begins, and numChars specifies the number of characters to
use.
• char chars[] = {'a','b','c','d','e','f'};
String s = new String(chars,2,3);
• This initializes s with the characters cde.
• String(String strObj) initializes string with the value
of another string
String APIs
String s1="Hello";
s1.length(); gives the length of string
int age =25;
String s2=“I am“+age+”years young”;
• When Java converts data into its string representation during
concatenation, it does so by calling one of the overloaded
versions of the string conversion method valueOf() defined
by String.
• valueOf() is overloaded for all the simple types and
for type Object.
• For the simple types, valueOf( ) returns a string that
contains the human-readable equivalent of
the value with which it is called.
• Every class implements toString() because it is
defined by Object.
• For the classes we create we want to override
toString() and provide our own string representations.
• The toString() method has this general form:
String toString()
• To implement toString(),simply return a String
object that contains the human-readable string that
appropriately describes an object of your class.
• Ref:ToStringAppln.java
StringBuffer
• StringBuffer is a peer class of String that
provides much of the functionality of strings.
• String represents fixed-length, immutable
character sequences. In contrast, StringBuffer
represents growable and writeable character
sequences.
• StringBuffer may have characters and
substrings inserted in the middle or appended
to
the end. StringBuffer will automatically grow to
make room for such additions Java uses both
classes heavily, but many programmers deal
only with String and let
• Java manipulate StringBuffers behind the
scenes by using the overloaded + operator.
• Write a program that implements string editor
Java.lang
• java.lang is automatically imported into all
programs. It is Java's most widely used
package.
• Contains classes and interfaces that are
fundamental to virtually all of Java
programming.
• This package contains lots of classes and three
interfaces.Clonable,Runnable and
Comparable
• Java uses simple types, such as int and
char, for performance reasons. These data
types are not part of the object hierarchy. They
are passed by value to methods and cannot be
directly passed by reference.
• There is no way for two methods to refer to the
same instance of an int.
• There are situations where we need objects
than primitive types to store the value.In such a
situation to store a simple type in one of these
classes, we need to wrap the simple type in a
class.
• To address the above situation java provides
wrapper classes.These classes encapsulate, or
wrap, the simple types within a class.
• The abstract class Number defines a
superclass that is implemented by the classes
that wrap the numeric types byte, short, int,
long, float, and double.
• has abstract methods that return the value of
Number the object in each of the different
number formats.
• That is, doubleValue( ) returns the value
as a double, floatValue( ) returns the
value as a float, and so on.
•
•
•
•
•
Number
Double and Float
Byte, Short, Integer, and Long
Character
Boolean
Download