Transcript PPT4

I / O in java
java.io
BufferedInputStream
BufferedOutputStream
BufferedReader
BufferedWriter
ByteArrayInputStream
ByteArrayOutputStream
CharArrayReader
CharArrayWriter
DataInputStream
DataOutputStream
File
FileDescriptor
FileInputStream
FileOutputStream
FilePermission
FileReader
FileWriter
FilterInputStream
FilterOutputStream
FilterReader
FilterWriter
InputStream
InputStreamReader
LineNumberInputStream
LineNumberReader
ObjectInputStream
ObjectInputStream.GetField
ObjectOutputStream
ObjectOutputStream.PutField
ObjectStreamClass
ObjectStreamField
OutputStream
OutputStreamWriter
PipedInputStream
PipedOutputStream
PipedReader
PipedWriter
PrintStream
PrintWriter
PushbackInputStream
PushbackReader
RandomAccessFile
Reader
SequenceInputStream
SerializablePermission
StreamTokenizer
StringBufferInputStream
StringReader
StringWriter
Writer
Topics to be covered
• I/O Streams
– Byte Streams handle I/O of raw binary data.
– Character Streams handle I/O of character data, automatically handling translation to
and from the local character set.
– Buffered Streams optimize input and output by reducing the number of calls to the
native API.
– Scanning and Formatting allows a program to read and write formatted text.
– I/O from the Command Line describes the Standard Streams and the Console object.
– *Data Streams handle binary I/O of primitive data type and String values.
– *Object Streams handle binary I/O of objects.
• File I/O
– File Objects help you to write platform-independent code that examines and
manipulates files.
– *Random Access Files handle non-sequential file access.
* To be covered, by yourself
I/O Streams
• Java program perform all I/O operations through streams
• A stream is an abstraction that either consumes or produces
information
• An input stream produces a stream of characters; an output
stream receives a stream of characters, “one at a time.”
• All streams behave in a similar manner(independent of the
device, they are linked to;viz diskfile, console or a network
socket)
• Java implements streams within class hierarchies defined in
java.io package.
Byte Streams
• Byte streams provide a convenient means for handling input
and output of bytes.
• These are used, when reading or writing binary data.
• Byte streams are defined by using two class hierarchies.At
the top are two abstract classes : InputStream, OutputStream
• The abstract classes InputStream and OutputStream define
several key methods that the other stream classes implement.
Two most important methods are read() and write().
• The following programs uses byte streams to perform input
and output of 8-bit bytes. All byte stream classes are
descended from InputStream and OutputStream.
• There are many byte stream classes. Here the
FileInputStream and FileOutputStreams are being used.
• Byte streams should only be used for the most primitive I/O
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyBytes {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(“in.txt");
out = new FileOutputStream("out.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
} //while
}//try
finally {
if (in != null) {
in.close(); }
if (out != null) {
out.close();
}}}}
Character Streams
• Character Streams provide a convenient way for
handling input and output of characters.
• They use Unicode and therefore can be
internationalized.
• In most cases character streams are more efficient
than byte streams.
• The lowest level IO is still byteoriented.
• In character Streams at the top there are two classes
Reader and Writer.
• These two classes define several methods out of
these read() and write() are the two important ones.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CopyCharacters {
public static void main(String[] args) throws IOException {
FileReader inputStream = null;
FileWriter outputStream = null;
try {
inputStream = new FileReader(“in.txt");
outputStream = new FileWriter(“out.txt");
int c;
while ((c = inputStream.read()) != -1) {
outputStream.write(c);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
Reading Console Input
• The preferred method of reading console input for Java is to use character
oriented streams
• In Java, console input is accomplished by reading from System.in(predefined
stream), which is wrapped in BufferedReader object.
• In case of unbuffered io the read and write requests are handled by underlying
os. This can make a program much less efficient, since each such request often
triggers disk access, network activity, or some other operation that is relatively.
• To reduce this kind of overhead, the Java platform implements buffered I/O
streams. Buffered input streams read data from a memory area known as a
buffer; the native input API is called only when the buffer is empty. Similarly,
buffered output streams write data to a buffer, and the native output API is
called only when the buffer is full
• A program can convert a unbuffered stream into a buffered stream using the
wrapping idiom we've used several times now
– inputStream = new BufferedReader(new FileReader(“in.txt"));
– outputStream = new BufferedWriter(new FileWriter(“out.txt"));
Import java.io.*;
Class consoleRead {
public static void main(String s[]) throws IOException{
char c;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println(“Enter characters, q to quit”);
do{
c=(char) br.read();
system.out.println©;
}while(c!=‘q’);
}
}
}
Reading/Writing Strings/Lines
• Character I/O usually occur in bigger units
than single characters
import java.io.*;
public class CopyLines {
public static void main(String[] args) throws IOException {
BufferedReader inputStream = null;
PrintWriter outputStream = null;
try {
inputStream = new BufferedReader(new FileReader("xanadu.txt"));
outputStream = new PrintWriter(new FileWriter("characteroutput.txt"));
String l;
while ((l = inputStream.readLine()) != null) {
outputStream.println(l);
Import java.io.*;
}
Class ReadLines {
} finally {
Public static void main(String s[]) throws IOExcep
if (inputStream != null) {
inputStream.close();
BufferedReader br=new BufferedReade
}
InputStreamReader(system.in));
if (outputStream != null) {
String str;
outputStream.close();
str=br.readLine();
}
} }}
System.out.println(str);
}
File
• File class doesnot operate on streams
• It donot specify how information is being
retrieved from or stored in files; but the
properties of a file itself.
• Constructors
– File(String directorypath)
– File(String directorypath, String filename)
– File(File dirObj, String filename)
Import java.io.*;
Class filedemo{
Static void P(String s){System.out.println(s);}
public static void main(String s[]) throws IOException {
File f1= new File( “c:/jdk1.4/bin/COPYRIGHT”);
Other methods
P(“file name:”+f1.getName());
getParent()
P(“Path:”+f1.getPath();
exists()
P(“Abs Path :”+f1.getAbsolutePath());
canWrite()
}
canRead()
}
isDirectory()
isFile()
lastModified()
length()
list()
Formatted Output
•
•
Use DecimalFormat to control spacing and
formatting (java has no printf statement)
Approach
1. Create a DecimalFormat object describing the
formatting
DecimalFormat formatter=new DecimalFormat(“#,###.##”);
2. Then use the format method to convert values into
formatted strings
formatter.format(24.99);
Formatting Characters
Symbol
Meaning
0
Placeholder for digit
#
.
Placeholder for digit without showing
training zeros
Location of decimal point
,
Location of Comma
-
Minus Sign
E
Scientific Notation
%
Multiply the value by 100 and display as
NumberFormat Example
Import java.text.*;
Public class NumberFormat {
public static void main(String s[]) {
DecimalFormat science=new DecimalFormat(“0.000E0”);
DecimalFormat plain=new DecimalFormat(“0.0000”);
for (double d=100.0;d<140.0;d*=1.10)
{
System.out.println(“Scientific : “+ science.format(d) +
“ and plain : “ + plain.format(d));
}}}
Alternate format specification
public class Root2 {
public static void main(String[] args) {
int i = 2;
double r = Math.sqrt(i);
System.out.format("The square root of %d is %f.%n", i, r);
}
•d formats an integer value as a decimal value.
}
•f formats a floating point value as a decimal value.
•n outputs a platform-specific line terminator.
•x formats an integer as a hexadecimal value.
•s formats any value as a string.
•tB formats an integer as a locale-specific month name.
There are many other conversions.
Serialization
• Just as data streams support I/O of primitive data types,
object streams support I/O of objects
• Most, but not all, standard classes support serialization of
their objects. Those that do implement the marker
interface Serializable.
• The object stream classes are ObjectInputStream and
ObjectOutputStream.
These
classes
implement
ObjectInput and ObjectOutput, which are subinterfaces of
DataInput and DataOutput