SlideShare une entreprise Scribd logo
1  sur  61
Jan. 2004 1
Java I/O
Yangjun Chen
Dept. Business Computing
University of Winnipeg
Jan. 2004 2
Outline: I/O Streams
• I/O Streams
- Byte stream: Input Stream and Output Stream
- Filter Stream
- Buffered Stream
- Data Stream
- Print Stream
- File Stream
- Character Stream: Reader and Writer
- Input Stream Reader and Output Stream Writer
- Buffered Reader/Writer
- File Reader/Writer
Jan. 2004 3
I/O Streams
• What is a stream?
- A stream is a sequence of data of undetermined length.
- Input streams move data into a Java program usually from an external
source.
- Output streams move data from a Java program to an external target.
• Java Streams
- A Java stream is composed of discrete bytes (characters) of data.
Jan. 2004 4
Object
InputStream
Byte Streams
OutputStream
FileInputStream
FilterInputStream
FileOutputStream
FilterOutputStream
BufferedInputStream
DataInputStream
BufferedOutputStream
DataOutputStream
PrintStream
Jan. 2004 5
Object
Reader
Character Streams
writer
BufferedReader
InputStreamReader FileReader
BufferedWriter
OutputStreamWriter
PrintWriter
FileWriter
Jan. 2004 6
InputStream Class
• java.io.InputStream is an abstract class for all input streams.
• It contains methods for reading in raw bytes of data from input
stream: key board, files, network client.
- public abstract int read()
- public int read (byte[] buf)
- public int read(byte[] buf, int offset, int length)
Jan. 2004 7
InputStream Class
- public long skip(long n)
. skip n number of bytes
- public int available( )
. how many bytes can be read before blocking
- pcublic void close( )
- public synchronized void mark (int readlimit)
. bookmark current position in the stream
- public boolean markSupported( )
- public synchronized void reset( )
. rewind the stream to the marked position
• All but the last two methods throw an IOException.
Jan. 2004 8
The read( ) method
• The basic read() method reads a single unsigned byte of data
and returns the integer value of the unsigned byte.
• This is a number between 0 and 255
• Returns a -1 if the end of a stream is encountered.
• The method blocks until input data are available, the end of
stream is detected or an exception is thrown.
Jan. 2004 9
The read( ) method
int[] data = new int[10];
for (int i =0; i <data.length, i++)
data [i]= System.in.read( );
}
• This code reads in 10 bytes from the System.in input stream
and stores it in the int array data.
• Notice that although read() reads in a byte, it returns a value of
type int. If you want the raw byte, cast the int into a byte.
Jan. 2004 10
The read( ) method
• read() has a possibility of throwing an exception.
try {
int data[] = new int[10] ;
for (int i=0; i<data.length; i++) {
int datum = System.in.read();
if (datum == -1) break;
data[il = datum;
}//for
}//try
catch (IOException e) {
System.err.println(e);
}
End of stream
Jan. 2004 11
The read( ) method
• The value of -1 is returned when the end of stream is reached.
This can be used as a check for the stream end.
• Remember that read() blocks. So if there is any other
important work to do in your program, try to put your I/O in a
separate thread.
• read() is abstract method defined in InputStream. This means
you can't instantiate InputStream directly: work with one of it's
subclasses instead.
Jan. 2004 12
Echo Example(l)
import java.io.*,
public class Echo {
public static void main(String[] args){
echo(System.in);
}//main
public static void echo(InputStream is) {
try {
for (int j = 0; j < 20; j++) {int i = is.read( );
BufferedInputStream
An instance of a subclass
of InputStream
(remember: upcasting)
Jan. 2004 13
Echo Example(2)
// -1 returned for end of stream
if (i == -1)
break;
char c = (char) i ;
System.out.print(c);
}//for loop
}//try
catch (IOException e){
System.err.println();
}//catch
System.out.println( );
}//echo method
}//Echo class
Jan. 2004 14
Reading Multiple Bytes
• Since accessing I/O is slow in comparison to memory access,
limiting the number of reads and writes is essential.
• The basic read() method only reads in a byte at a time.
• The following two overloading read() methods read in multiple
bytes into an array of bytes.
- public int read(byte b[])
- public int read(byte b[], int offset, int length)
Jan. 2004 15
Reading Multiple Bytes
• The first method tries to read enough bytes to fill the array b[].
try {
byte[ ] b = new byte[10];
int j = Svstem.in.read(b);
}
catch (IOException e){ }
• This method blocks until data are available just like the read()
method.
Jan. 2004 16
Reading Multiple Bytes
• The second method reads length bytes from the input stream
and stores them in the array b[] starting at the location offset.
try {//what does this loop do
byte[] b = new byte[100];
int offset = 0;
while (offset < b.length) {
int bytesRead = System.in.read(b, offset, b.length - offset);
if (bytesRead == -1) break;
offset += bytesRead; }//while
catch (IOException e){}
Jan. 2004 17
Closing Input Streams
• For well behaved programs, all streams should be closed
before exiting the program.
• Allows OS to free any resources associated with the stream.
• Use the close() method
- public void close() throws IOException
• Not all streams have to be closed.
- System.in does not have to be closed.
Jan. 2004 18
Closing Input Streams
try {
URL u = new URL(“http://java.sun.com”);
InputStream in = u.openStream();
/ read from stream ...
in.close();
}
catch (IOException e){}
• Once an input stream has been closed, you can no longer read
from it. Doing so will cause an IOException to be thrown.
Jan. 2004 19
Reading from File Input Streams
import java.io.*;
class FileInputStreamDemo {
public static void main(String args[]) {
try {//Create a file input stream
FileInputStream fis = new FileInputStream(args[0]);
//read 12 byte from the file
int i;
while ((i = fis.read()) != -1)
{System.out.println(i);}
//Close file output stream
fis.close();
}catch(Exception e) {System.out.println(“Exception: ” + e);}
}}
Jan. 2004 20
Reading from Buffered Input Streams
import java.io.*;
class FileBufferedStreamDemo {
public static void main(String args[]) {
try {//Create a file input stream
FileInputStream fis = new FileInputStream(args[0]);
//Create a buffered input stream
BufferedInputStream bis = new BufferedInputStream(fis);
//read 12 byte from the file
int i;
while ((i = bis.read()) != -1)
{System.out.println(i);}
//Close file output stream
fis.close();
}catch(Exception e) {System.out.println(“Exception: ” + e);}
}}
Jan. 2004 21
Reading from Data Input Streams
import java.io.*;
class DataInputStreamDemo {
public static void main(String args[]) {
try {//Create a file input stream
FileInputStream fis = new FileInputStream(args[0]);
//Create a data input straem
DataInputStream dis = new DataInputStream(fis);
//read and display data
System.out.println(dis.readBoolean());
System.out.println(dis.readByte());
Jan. 2004 22
Reading from Data Input Streams
System.out.println(dis.readChar());
System.out.println(dis.readDouble());
System.out.println(dis.readFloat());
System.out.println(dis.readInt());
System.out.println(dis.readLong());
System.out.println(dis.readShort());
//Close file input stream
fis.close();
}catch(Exception e) {System.out.println(“Exception: ” + e);}
}}
Jan. 2004 23
Output Streams
• java.io.OutputStream class sends raw bytes of data to a target
such as the console, a file, or a network server.
• Methods within this class are:
- public abstract void write(int b)
- public void write(byte b[])
- public void write(byte b[], int offset, int length)
- public void flush()
- public void close()
• All methods throw an IOException
Jan. 2004 24
Output Streams
• The write() methods sends raw bytes of data to whomever is
listening to the stream.
• Sometimes for performance reasons, the operating system
buffers output streams.
• When the buffer fills up, the data are all written at once.
• The flush() method will force the data to be written whether
the buffer is full or not.
Jan. 2004 25
Writing to Output Streams
• The fundamental method in OutputStream is write()
• public abstract void write(byte b)
• This method writes a single unsigned byte of data that should
be between 0 and 255.
• Larger numbers are reduced modulo 256 before writing.
Jan. 2004 26
Ascii Chart Example
import java.io.*;
public class AsciiChart{
public static void main(String args[]) {
for (int i=32; i<127; i++)
System.out.write(i);
//break line after every 8 characters
if (i%8 == 7) System.out.write(‘n’);
else System.out.write(‘t’);
}//for
System.out.write(‘n’);
}//main
}//class
Jan. 2004 27
Writing Arrays of Bytes
• The two remaining write methods write multiple bytes of data.
- Public void write(byte b[])
- Public void write(byte b[], int offset, int length)
• The first writes an entire byte array of data, while the second
writes a sub-array of data starting at offset and continuing for
length bytes.
• Remember that these methods write bytes, so data must be
converted into bytes.
Jan. 2004 28
AsciiArray Example
import java.io.*;
public class AsciiArray{
public static void main(String args[]) {
int index=O;
byte[] b = new byte[(127-31)*2];
for (int i=32; i<127; i++) {
b[index++] = (byte)i;
//break line after every 8 characters
if (i%8==7) b[index++] = (byte)‘n’;
else b[index++] = (byte) ‘t’;
Jan. 2004 29
AsciiArray Example
}//for
b[index++] = (byte) ‘n’;
try {
System.out.write(b);
}
catch(IOException e) {}
}//main
}//class
• The output is the same as AsciiChart.
Jan. 2004 30
Writing to File Output Streams
import java.io.*;
class FileOutputStreamDemo {
public static void main(String args[]) {
try {//Create a file output stream
FileOutputStream fos = new FileOutputStream(args[0]);
//Write 12 byte to the file
for (int i = 0; i < 12; i++) {
fos.write(i);}
//Close file output stream
fos.close();
}catch(Exception e) {System.out.println(“Exception: ” + e);}
}}
Jan. 2004 31
Flushing and Closing Output Streams
• As mentioned, many operating systems buffer output data to
improve performance.
• Rather than sending a bytes at a time, bytes are accumulated
until the buffer is full, and one write occurs.
• The flush() method forces the data to be written even if the
buffer is not full.
- public void flush( ) throws IOException
• Like input streams, output streams should be closed. For
output streams, closing them will also flush the contents of the
buffer.
Jan. 2004 32
Filter Streams
• java. io.FilterInputStream and java. io.FilterOutputStream
are subclasses of InputStream and OutputStream, respectively.
• These classes are rarely used, but their subclasses are extremely
important.
Jan. 2004 33
Filter Streams Classes
• Buffered Streams
- These classes will buffer reads and writes by first reading the data into
a buffer(array of bytes)
• Data Streams
- These classes read and write primitive data types and Strings.
• Print Stream
- referenced by System.out and System.err.
- It uses the platforms default character encoding to convert characters
into bytes.
Jan. 2004 34
Buffered Streams
• Buffered input stream read more data than initially needed and
store them in a buffer.
• So when the buffered stream's read() method is called, the data
is removed from the buffer rather than from the underlying
system.
• When the buffer is empty, the buffered stream refills the
buffer.
• Buffered output stream store data in an internal byte array until
the buffer is full or the stream is flushed. The data is then
written out once.
Jan. 2004 35
Buffered Streams
• Constructors
- BufferedInputStream(InputStream in)
- BufferedInputStream(Inputftream in, int size)
- BufferedOutputStream(OutputStream out)
- BufferedOutputStream(CrutputStream out, int size)
• The size argument is the size of the buffer.
• If not specified, a default of 512 bytes is used.
Jan. 2004 36
Buffered Streams
• Example:
URL u=new URL(“httP://java.sun.Com”);
BufferedInputStream bis;
bis= new BufferedlnputStream(u.openStream( ), 256)
• BufferedInputStreamand and BufferedOutputStream do not
declare any new methods but rather override methods from
Inputstream and outputstream, respectively.
Jan. 2004 37
Writing to Buffered Output Streams
import java.io.*;
class BufferedOutputStreamDemo {
public static void main(String args[]) {
try {//Create a file output stream
FileOutputStream fos = new FileOutputStream(args[0]);
//Create a buffered output straem
BufferedOutputStream bos = new BufferedOutputStream(fos);
//Write 12 byte to the file
for (int i = 0; i < 12; i++) {
bos.write(i);}
//Close file output stream
bos.close(); fos.close();
}catch(Exception e) {System.out.println(“Exception: ” + e);}
}}
Jan. 2004 38
Data Streams
• java.io.DataInputStream and java.io.DataOutputStream read
and write primitive data types and strings using the
java.io.DataInputand java.io.DataOutput interfaces,
respectively.
Jan. 2004 39
Data Streams
• Generally you use DataInputStream to read data written by
DataOutputStream
• public DataInputStrem(InputStream in)
• public DataOutputStream(OutputStream out)
• The usual methods associated with input and output streams
are present in data stream as well.
• However, data streams have other methods that allow them to
read and write primitive type.
Jan. 2004 40
Writing to Data Output Streams
import java.io.*;
class DataOutputStreamDemo {
public static void main(String args[]) {
try {//Create a file output stream
FileOutputStream fos = new FileOutputStream(args[0]);
//Create a data output straem
DataOutputStream dos = new DataOutputStream(fos);
//Write various types of data to the file
dos.writeBoolean(false);
dos.writeByte(Byte.MAX_VALUE);
Jan. 2004 41
Writing to Data Output Streams
dos.writeChar(‘A’);
dos.writeDouble(Double.MAX_VALUE);
dos.writeFloat(Float. MAX_VALUE);
dos.writeInt(int. MAX_VALUE);
dos.writeLong(Long. MAX_VALUE);
dos.writeShort(Short. MAX_VALUE);
//Close file output stream
fos.close();
}catch(Exception e) {System.out.println(“Exception: ” + e);}
}}
Jan. 2004 42
Print Streams
• Allows very simple printing of both primitive values, objects,
string literals.
• There are many overloaded print( ) and println( ) methods.
• This method is deprecated in Java 1.1.
• The biggest problem with this class is that it does not properly
handle international character sets.
• Use the PrintWriter class instead.
Jan. 2004 43
Readers and Writers
• Classes that read and write character based data.
• These characters can have varying widths depending on the
character set being used.
• Readers and writers know how to handle many different
character sets.
Jan. 2004 44
Reader Class
• java.io.Reader
• This class is deliberately similar to the java.io.InputStream
class.
• Methods in the Reader class are similar to the InputStream
class except that the methods work on characters not bytes.
Jan. 2004 45
Writer Class
• Java.io.Writer
• This class is similar to the
java.io.OutputStream class.
• Methods in the Writer class now work on characters and not
bytes.
Jan. 2004 46
InputStreamReader
• java. io.InputStreamReader acts as a translater between byte
streams and character streams.
• It reads bytes from the input stream and translates them into
characters according to a specified character encoding.
Jan. 2004 47
InputStreamReader Class
• You can set the encoding scheme or you can use the platforms
default setting.
• public InputstreamReader(Inputstream in)
• public InputStreamReader(InputStream in, String enc)
throws UnsupportedEncoding Exception
Jan. 2004 48
OutputStreamWriter
• java. io.OutputStreamWriter will write bytes of data to the
output stream after translating the characters according to the
specified encoding.
• public OutputStreamWriter(OutputStream out)
• public OutputStreamWriter(OutputStream out, String enc)
throws UnsupportedEncodingException
Jan. 2004 49
Buffered Reads/Writes
• There are classes that allow for a more efficient reading and
writing of characters by buffering.
• java.io.BufferedReader
• java.io.BufferedWriter
• These classes are similar to the Buffered Stream classes.
• Most notable for the readLine() Method. This allows data to be
read a line at a time.
• public String readLine() throws IOException
Jan. 2004 50
Buffered Reads/Writes
import java.io.*;
public class StringInputFile {
public static void main(String[] arg) throws Exception {
PrintStream backup;
FileOutputStream backupFileStream;
File backupFile;
backupFile = new File(“backup”);
backupFileStream = new FileOutputStream(backupFile);
backup = new PrintStream(backupFileStream);
Jan. 2004 51
System.out.println(“This is my first data file”);
backup.println(“This is my first data file”);
System.out.println(“... but it won't be my last”);
backup.println(“... but it won’t be my last”);
}
}
Buffered Reads/Writes
Jan. 2004 52
Writing output to a file involves three steps as follows:
• Create an File object
• Create an FileOutputStream object
• Create a PrintStream object
Buffered Reads/Writes
Jan. 2004 53
Buffered Reads/Writes
import java.io.*;
public class StringInputFile {
public static void main(String[] arg) throws Exception {
InputStreamReader backup;
BufferedReader br;
FileInputStream backupFileStream;
File backupFile;
String inputline;
Jan. 2004 54
backupFile = new File(“backup”);
backupFileStream = new FileInputStream(backupFile);
backup = new InputStreamReader(backupFileStream);
br = new BufferedReader(backup);
inputline = br.readLine();
System.out.println(inputline);
inputline = br.readLine();
System.out.println(inputline);
}
}
Buffered Reads/Writes
Jan. 2004 55
Reading data from a file involves three steps as follows:
• Create an FileInputStream or BufferedInputStream object
• Create an InputStreamReader object which we use to
• Create a BufferedReader object
Buffered Reads/Writes
Jan. 2004 56
Example: Send Data(l)
import java.net.*; import java.io.*;
public class SendData extends Thread {
Socket sock;
public SendData (Socket sock) {
this.sock = sock;
}//SendData constructor
public void run() {
string line;
Jan. 2004 57
Example: Send Data(2)
try {
OutputStreamWriter outw=new
outputstreamwriter(sock.getOutputStream());
BufferedWriter sockout=new
BufferedWriter(outw);
InputStreamReader inr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(inr);
while ((line = in.readLine()) != null) {
sockout.write(line+ “n”);
Jan. 2004 58
Example: Send Data(3)
sockout.flush(); yield( );
}//while
} //try
catch (java.io.IoException e) {
System.out.println(e);
System.exit(0);
}//catch
} //run
}//SendData
Jan. 2004 59
Example: Receive Data(l)
import java.net.*;
import java.io.*;
public class RcveData extends Thread {
Socket sock;
public RcveData(Socket sock) {
this.sock = sock;
}
public void run() {
String line;
Jan. 2004 60
Example: Receive Data(2)
try {
InputStreamReader inr = new
InputStreamReader(sock.getlnputStream());
BufferedReader in = new BufferedReader(inr);
while ((line = in.readLine()) != null) {
System.out.print(mReceiving:
System.out.println(line);
yield();
}//while
)//try
Jan. 2004 61
Example: Receive Data(3)
catch (java.io.IOException e) {
System.out.println(e);
System.exit(0);
I }//catch
}//run
}//RCVeData

Contenu connexe

Tendances

Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsAnton Keks
 
working file handling in cpp overview
working file handling in cpp overviewworking file handling in cpp overview
working file handling in cpp overviewgourav kottawar
 
Files & IO in Java
Files & IO in JavaFiles & IO in Java
Files & IO in JavaCIB Egypt
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)Om Ganesh
 
Byte stream classes.49
Byte stream classes.49Byte stream classes.49
Byte stream classes.49myrajendra
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams Ahmed Farag
 
L21 io streams
L21 io streamsL21 io streams
L21 io streamsteach4uin
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handlingpinkpreet_kaur
 
[Java] #7 - Input & Output Stream
[Java] #7 - Input & Output Stream[Java] #7 - Input & Output Stream
[Java] #7 - Input & Output StreamGhadeer AlHasan
 
Data file handling
Data file handlingData file handling
Data file handlingTAlha MAlik
 
I/O in java Part 1
I/O in java Part 1I/O in java Part 1
I/O in java Part 1ashishspace
 
File Input & Output
File Input & OutputFile Input & Output
File Input & OutputPRN USM
 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and filesMarcello Thiry
 

Tendances (20)

Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
working file handling in cpp overview
working file handling in cpp overviewworking file handling in cpp overview
working file handling in cpp overview
 
Files & IO in Java
Files & IO in JavaFiles & IO in Java
Files & IO in Java
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
 
Java stream
Java streamJava stream
Java stream
 
Byte stream classes.49
Byte stream classes.49Byte stream classes.49
Byte stream classes.49
 
Java Streams
Java StreamsJava Streams
Java Streams
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
 
Input output streams
Input output streamsInput output streams
Input output streams
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
[Java] #7 - Input & Output Stream
[Java] #7 - Input & Output Stream[Java] #7 - Input & Output Stream
[Java] #7 - Input & Output Stream
 
Java I/O
Java I/OJava I/O
Java I/O
 
Data file handling
Data file handlingData file handling
Data file handling
 
Java file
Java fileJava file
Java file
 
I/O in java Part 1
I/O in java Part 1I/O in java Part 1
I/O in java Part 1
 
File Input & Output
File Input & OutputFile Input & Output
File Input & Output
 
Files and streams
Files and streamsFiles and streams
Files and streams
 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and files
 

En vedette

Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & OutputItp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Outputphanleson
 
Remote method invocation (as part of the the PTT lecture)
Remote method invocation (as part of the the PTT lecture)Remote method invocation (as part of the the PTT lecture)
Remote method invocation (as part of the the PTT lecture)Ralf Laemmel
 
Threadlifecycle.36
Threadlifecycle.36Threadlifecycle.36
Threadlifecycle.36myrajendra
 
IO and serialization
IO and serializationIO and serialization
IO and serializationbackdoor
 
Ejb 2.0
Ejb 2.0Ejb 2.0
Ejb 2.0sukace
 
Elasticsearch Aggregations
Elasticsearch AggregationsElasticsearch Aggregations
Elasticsearch AggregationsWaldemar Neto
 
Servlet/JSP course chapter 1: Introduction to servlets
Servlet/JSP course chapter 1: Introduction to servletsServlet/JSP course chapter 1: Introduction to servlets
Servlet/JSP course chapter 1: Introduction to servletsJavaEE Trainers
 
Remote Method Invocation
Remote Method InvocationRemote Method Invocation
Remote Method InvocationPaul Pajo
 
Java EE 8: What Servlet 4.0 and HTTP/2 mean to you
Java EE 8: What Servlet 4.0 and HTTP/2 mean to youJava EE 8: What Servlet 4.0 and HTTP/2 mean to you
Java EE 8: What Servlet 4.0 and HTTP/2 mean to youAlex Theedom
 
Thread Dump Analysis
Thread Dump AnalysisThread Dump Analysis
Thread Dump AnalysisDmitry Buzdin
 
Java Multi Thead Programming
Java Multi Thead ProgrammingJava Multi Thead Programming
Java Multi Thead ProgrammingNishant Mevawala
 

En vedette (20)

Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & OutputItp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
 
Data structures2
Data structures2Data structures2
Data structures2
 
Java API, Exceptions and IO
Java API, Exceptions and IOJava API, Exceptions and IO
Java API, Exceptions and IO
 
32.java input-output
32.java input-output32.java input-output
32.java input-output
 
Remote method invocation (as part of the the PTT lecture)
Remote method invocation (as part of the the PTT lecture)Remote method invocation (as part of the the PTT lecture)
Remote method invocation (as part of the the PTT lecture)
 
Threadlifecycle.36
Threadlifecycle.36Threadlifecycle.36
Threadlifecycle.36
 
Javaiostream
JavaiostreamJavaiostream
Javaiostream
 
enterprise java bean
enterprise java beanenterprise java bean
enterprise java bean
 
Javaiostream
JavaiostreamJavaiostream
Javaiostream
 
IO and serialization
IO and serializationIO and serialization
IO and serialization
 
Ejb 2.0
Ejb 2.0Ejb 2.0
Ejb 2.0
 
Elasticsearch Aggregations
Elasticsearch AggregationsElasticsearch Aggregations
Elasticsearch Aggregations
 
Servlet/JSP course chapter 1: Introduction to servlets
Servlet/JSP course chapter 1: Introduction to servletsServlet/JSP course chapter 1: Introduction to servlets
Servlet/JSP course chapter 1: Introduction to servlets
 
Md121 streams
Md121 streamsMd121 streams
Md121 streams
 
Java exception
Java exception Java exception
Java exception
 
Remote Method Invocation
Remote Method InvocationRemote Method Invocation
Remote Method Invocation
 
Java EE 8: What Servlet 4.0 and HTTP/2 mean to you
Java EE 8: What Servlet 4.0 and HTTP/2 mean to youJava EE 8: What Servlet 4.0 and HTTP/2 mean to you
Java EE 8: What Servlet 4.0 and HTTP/2 mean to you
 
Thread Dump Analysis
Thread Dump AnalysisThread Dump Analysis
Thread Dump Analysis
 
Java Multi Thead Programming
Java Multi Thead ProgrammingJava Multi Thead Programming
Java Multi Thead Programming
 
Java bean
Java beanJava bean
Java bean
 

Similaire à Io stream

Similaire à Io stream (20)

Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
CORE JAVA-1
CORE JAVA-1CORE JAVA-1
CORE JAVA-1
 
Files and streams In Java
Files and streams In JavaFiles and streams In Java
Files and streams In Java
 
1.26 File Input-Output in JAVA.pptx
1.26 File Input-Output in JAVA.pptx1.26 File Input-Output in JAVA.pptx
1.26 File Input-Output in JAVA.pptx
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
 
Files io
Files ioFiles io
Files io
 
Io Streams
Io StreamsIo Streams
Io Streams
 
Java Day-6
Java Day-6Java Day-6
Java Day-6
 
What is java input and output stream?
What is java input and output stream?What is java input and output stream?
What is java input and output stream?
 
What is java input and output stream?
What is java input and output stream?What is java input and output stream?
What is java input and output stream?
 
Advanced programming ch2
Advanced programming ch2Advanced programming ch2
Advanced programming ch2
 
CPP17 - File IO
CPP17 - File IOCPP17 - File IO
CPP17 - File IO
 
Input/Output Exploring java.io
Input/Output Exploring java.ioInput/Output Exploring java.io
Input/Output Exploring java.io
 
26 io -ii file handling
26  io -ii  file handling26  io -ii  file handling
26 io -ii file handling
 
CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxCHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptx
 
ch09.ppt
ch09.pptch09.ppt
ch09.ppt
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
 
Data file handling
Data file handlingData file handling
Data file handling
 

Plus de Parthipan Parthi (20)

Inheritance
Inheritance Inheritance
Inheritance
 
Switch statement mcq
Switch statement  mcqSwitch statement  mcq
Switch statement mcq
 
Oprerator overloading
Oprerator overloadingOprerator overloading
Oprerator overloading
 
802.11 mac
802.11 mac802.11 mac
802.11 mac
 
Ieee 802.11 wireless lan
Ieee 802.11 wireless lanIeee 802.11 wireless lan
Ieee 802.11 wireless lan
 
Computer network
Computer networkComputer network
Computer network
 
Ieee 802.11 wireless lan
Ieee 802.11 wireless lanIeee 802.11 wireless lan
Ieee 802.11 wireless lan
 
Session 6
Session 6Session 6
Session 6
 
Queuing analysis
Queuing analysisQueuing analysis
Queuing analysis
 
WAP
WAPWAP
WAP
 
Alternative metrics
Alternative metricsAlternative metrics
Alternative metrics
 
Ethernet
EthernetEthernet
Ethernet
 
Ieee 802.11 wireless lan
Ieee 802.11 wireless lanIeee 802.11 wireless lan
Ieee 802.11 wireless lan
 
Data structures1
Data structures1Data structures1
Data structures1
 
Data structures 4
Data structures 4Data structures 4
Data structures 4
 
Data structures 3
Data structures 3Data structures 3
Data structures 3
 
Dbms lab questions
Dbms lab questionsDbms lab questions
Dbms lab questions
 
REVERSIBLE DATA HIDING WITH GOOD PAYLOAD DISTORTIONPpt 3
REVERSIBLE DATA HIDING WITH GOOD PAYLOAD DISTORTIONPpt 3 REVERSIBLE DATA HIDING WITH GOOD PAYLOAD DISTORTIONPpt 3
REVERSIBLE DATA HIDING WITH GOOD PAYLOAD DISTORTIONPpt 3
 
New syllabus combined_civil_services
New syllabus combined_civil_servicesNew syllabus combined_civil_services
New syllabus combined_civil_services
 
Pspice
PspicePspice
Pspice
 

Dernier

Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 

Dernier (20)

Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 

Io stream

  • 1. Jan. 2004 1 Java I/O Yangjun Chen Dept. Business Computing University of Winnipeg
  • 2. Jan. 2004 2 Outline: I/O Streams • I/O Streams - Byte stream: Input Stream and Output Stream - Filter Stream - Buffered Stream - Data Stream - Print Stream - File Stream - Character Stream: Reader and Writer - Input Stream Reader and Output Stream Writer - Buffered Reader/Writer - File Reader/Writer
  • 3. Jan. 2004 3 I/O Streams • What is a stream? - A stream is a sequence of data of undetermined length. - Input streams move data into a Java program usually from an external source. - Output streams move data from a Java program to an external target. • Java Streams - A Java stream is composed of discrete bytes (characters) of data.
  • 4. Jan. 2004 4 Object InputStream Byte Streams OutputStream FileInputStream FilterInputStream FileOutputStream FilterOutputStream BufferedInputStream DataInputStream BufferedOutputStream DataOutputStream PrintStream
  • 5. Jan. 2004 5 Object Reader Character Streams writer BufferedReader InputStreamReader FileReader BufferedWriter OutputStreamWriter PrintWriter FileWriter
  • 6. Jan. 2004 6 InputStream Class • java.io.InputStream is an abstract class for all input streams. • It contains methods for reading in raw bytes of data from input stream: key board, files, network client. - public abstract int read() - public int read (byte[] buf) - public int read(byte[] buf, int offset, int length)
  • 7. Jan. 2004 7 InputStream Class - public long skip(long n) . skip n number of bytes - public int available( ) . how many bytes can be read before blocking - pcublic void close( ) - public synchronized void mark (int readlimit) . bookmark current position in the stream - public boolean markSupported( ) - public synchronized void reset( ) . rewind the stream to the marked position • All but the last two methods throw an IOException.
  • 8. Jan. 2004 8 The read( ) method • The basic read() method reads a single unsigned byte of data and returns the integer value of the unsigned byte. • This is a number between 0 and 255 • Returns a -1 if the end of a stream is encountered. • The method blocks until input data are available, the end of stream is detected or an exception is thrown.
  • 9. Jan. 2004 9 The read( ) method int[] data = new int[10]; for (int i =0; i <data.length, i++) data [i]= System.in.read( ); } • This code reads in 10 bytes from the System.in input stream and stores it in the int array data. • Notice that although read() reads in a byte, it returns a value of type int. If you want the raw byte, cast the int into a byte.
  • 10. Jan. 2004 10 The read( ) method • read() has a possibility of throwing an exception. try { int data[] = new int[10] ; for (int i=0; i<data.length; i++) { int datum = System.in.read(); if (datum == -1) break; data[il = datum; }//for }//try catch (IOException e) { System.err.println(e); } End of stream
  • 11. Jan. 2004 11 The read( ) method • The value of -1 is returned when the end of stream is reached. This can be used as a check for the stream end. • Remember that read() blocks. So if there is any other important work to do in your program, try to put your I/O in a separate thread. • read() is abstract method defined in InputStream. This means you can't instantiate InputStream directly: work with one of it's subclasses instead.
  • 12. Jan. 2004 12 Echo Example(l) import java.io.*, public class Echo { public static void main(String[] args){ echo(System.in); }//main public static void echo(InputStream is) { try { for (int j = 0; j < 20; j++) {int i = is.read( ); BufferedInputStream An instance of a subclass of InputStream (remember: upcasting)
  • 13. Jan. 2004 13 Echo Example(2) // -1 returned for end of stream if (i == -1) break; char c = (char) i ; System.out.print(c); }//for loop }//try catch (IOException e){ System.err.println(); }//catch System.out.println( ); }//echo method }//Echo class
  • 14. Jan. 2004 14 Reading Multiple Bytes • Since accessing I/O is slow in comparison to memory access, limiting the number of reads and writes is essential. • The basic read() method only reads in a byte at a time. • The following two overloading read() methods read in multiple bytes into an array of bytes. - public int read(byte b[]) - public int read(byte b[], int offset, int length)
  • 15. Jan. 2004 15 Reading Multiple Bytes • The first method tries to read enough bytes to fill the array b[]. try { byte[ ] b = new byte[10]; int j = Svstem.in.read(b); } catch (IOException e){ } • This method blocks until data are available just like the read() method.
  • 16. Jan. 2004 16 Reading Multiple Bytes • The second method reads length bytes from the input stream and stores them in the array b[] starting at the location offset. try {//what does this loop do byte[] b = new byte[100]; int offset = 0; while (offset < b.length) { int bytesRead = System.in.read(b, offset, b.length - offset); if (bytesRead == -1) break; offset += bytesRead; }//while catch (IOException e){}
  • 17. Jan. 2004 17 Closing Input Streams • For well behaved programs, all streams should be closed before exiting the program. • Allows OS to free any resources associated with the stream. • Use the close() method - public void close() throws IOException • Not all streams have to be closed. - System.in does not have to be closed.
  • 18. Jan. 2004 18 Closing Input Streams try { URL u = new URL(“http://java.sun.com”); InputStream in = u.openStream(); / read from stream ... in.close(); } catch (IOException e){} • Once an input stream has been closed, you can no longer read from it. Doing so will cause an IOException to be thrown.
  • 19. Jan. 2004 19 Reading from File Input Streams import java.io.*; class FileInputStreamDemo { public static void main(String args[]) { try {//Create a file input stream FileInputStream fis = new FileInputStream(args[0]); //read 12 byte from the file int i; while ((i = fis.read()) != -1) {System.out.println(i);} //Close file output stream fis.close(); }catch(Exception e) {System.out.println(“Exception: ” + e);} }}
  • 20. Jan. 2004 20 Reading from Buffered Input Streams import java.io.*; class FileBufferedStreamDemo { public static void main(String args[]) { try {//Create a file input stream FileInputStream fis = new FileInputStream(args[0]); //Create a buffered input stream BufferedInputStream bis = new BufferedInputStream(fis); //read 12 byte from the file int i; while ((i = bis.read()) != -1) {System.out.println(i);} //Close file output stream fis.close(); }catch(Exception e) {System.out.println(“Exception: ” + e);} }}
  • 21. Jan. 2004 21 Reading from Data Input Streams import java.io.*; class DataInputStreamDemo { public static void main(String args[]) { try {//Create a file input stream FileInputStream fis = new FileInputStream(args[0]); //Create a data input straem DataInputStream dis = new DataInputStream(fis); //read and display data System.out.println(dis.readBoolean()); System.out.println(dis.readByte());
  • 22. Jan. 2004 22 Reading from Data Input Streams System.out.println(dis.readChar()); System.out.println(dis.readDouble()); System.out.println(dis.readFloat()); System.out.println(dis.readInt()); System.out.println(dis.readLong()); System.out.println(dis.readShort()); //Close file input stream fis.close(); }catch(Exception e) {System.out.println(“Exception: ” + e);} }}
  • 23. Jan. 2004 23 Output Streams • java.io.OutputStream class sends raw bytes of data to a target such as the console, a file, or a network server. • Methods within this class are: - public abstract void write(int b) - public void write(byte b[]) - public void write(byte b[], int offset, int length) - public void flush() - public void close() • All methods throw an IOException
  • 24. Jan. 2004 24 Output Streams • The write() methods sends raw bytes of data to whomever is listening to the stream. • Sometimes for performance reasons, the operating system buffers output streams. • When the buffer fills up, the data are all written at once. • The flush() method will force the data to be written whether the buffer is full or not.
  • 25. Jan. 2004 25 Writing to Output Streams • The fundamental method in OutputStream is write() • public abstract void write(byte b) • This method writes a single unsigned byte of data that should be between 0 and 255. • Larger numbers are reduced modulo 256 before writing.
  • 26. Jan. 2004 26 Ascii Chart Example import java.io.*; public class AsciiChart{ public static void main(String args[]) { for (int i=32; i<127; i++) System.out.write(i); //break line after every 8 characters if (i%8 == 7) System.out.write(‘n’); else System.out.write(‘t’); }//for System.out.write(‘n’); }//main }//class
  • 27. Jan. 2004 27 Writing Arrays of Bytes • The two remaining write methods write multiple bytes of data. - Public void write(byte b[]) - Public void write(byte b[], int offset, int length) • The first writes an entire byte array of data, while the second writes a sub-array of data starting at offset and continuing for length bytes. • Remember that these methods write bytes, so data must be converted into bytes.
  • 28. Jan. 2004 28 AsciiArray Example import java.io.*; public class AsciiArray{ public static void main(String args[]) { int index=O; byte[] b = new byte[(127-31)*2]; for (int i=32; i<127; i++) { b[index++] = (byte)i; //break line after every 8 characters if (i%8==7) b[index++] = (byte)‘n’; else b[index++] = (byte) ‘t’;
  • 29. Jan. 2004 29 AsciiArray Example }//for b[index++] = (byte) ‘n’; try { System.out.write(b); } catch(IOException e) {} }//main }//class • The output is the same as AsciiChart.
  • 30. Jan. 2004 30 Writing to File Output Streams import java.io.*; class FileOutputStreamDemo { public static void main(String args[]) { try {//Create a file output stream FileOutputStream fos = new FileOutputStream(args[0]); //Write 12 byte to the file for (int i = 0; i < 12; i++) { fos.write(i);} //Close file output stream fos.close(); }catch(Exception e) {System.out.println(“Exception: ” + e);} }}
  • 31. Jan. 2004 31 Flushing and Closing Output Streams • As mentioned, many operating systems buffer output data to improve performance. • Rather than sending a bytes at a time, bytes are accumulated until the buffer is full, and one write occurs. • The flush() method forces the data to be written even if the buffer is not full. - public void flush( ) throws IOException • Like input streams, output streams should be closed. For output streams, closing them will also flush the contents of the buffer.
  • 32. Jan. 2004 32 Filter Streams • java. io.FilterInputStream and java. io.FilterOutputStream are subclasses of InputStream and OutputStream, respectively. • These classes are rarely used, but their subclasses are extremely important.
  • 33. Jan. 2004 33 Filter Streams Classes • Buffered Streams - These classes will buffer reads and writes by first reading the data into a buffer(array of bytes) • Data Streams - These classes read and write primitive data types and Strings. • Print Stream - referenced by System.out and System.err. - It uses the platforms default character encoding to convert characters into bytes.
  • 34. Jan. 2004 34 Buffered Streams • Buffered input stream read more data than initially needed and store them in a buffer. • So when the buffered stream's read() method is called, the data is removed from the buffer rather than from the underlying system. • When the buffer is empty, the buffered stream refills the buffer. • Buffered output stream store data in an internal byte array until the buffer is full or the stream is flushed. The data is then written out once.
  • 35. Jan. 2004 35 Buffered Streams • Constructors - BufferedInputStream(InputStream in) - BufferedInputStream(Inputftream in, int size) - BufferedOutputStream(OutputStream out) - BufferedOutputStream(CrutputStream out, int size) • The size argument is the size of the buffer. • If not specified, a default of 512 bytes is used.
  • 36. Jan. 2004 36 Buffered Streams • Example: URL u=new URL(“httP://java.sun.Com”); BufferedInputStream bis; bis= new BufferedlnputStream(u.openStream( ), 256) • BufferedInputStreamand and BufferedOutputStream do not declare any new methods but rather override methods from Inputstream and outputstream, respectively.
  • 37. Jan. 2004 37 Writing to Buffered Output Streams import java.io.*; class BufferedOutputStreamDemo { public static void main(String args[]) { try {//Create a file output stream FileOutputStream fos = new FileOutputStream(args[0]); //Create a buffered output straem BufferedOutputStream bos = new BufferedOutputStream(fos); //Write 12 byte to the file for (int i = 0; i < 12; i++) { bos.write(i);} //Close file output stream bos.close(); fos.close(); }catch(Exception e) {System.out.println(“Exception: ” + e);} }}
  • 38. Jan. 2004 38 Data Streams • java.io.DataInputStream and java.io.DataOutputStream read and write primitive data types and strings using the java.io.DataInputand java.io.DataOutput interfaces, respectively.
  • 39. Jan. 2004 39 Data Streams • Generally you use DataInputStream to read data written by DataOutputStream • public DataInputStrem(InputStream in) • public DataOutputStream(OutputStream out) • The usual methods associated with input and output streams are present in data stream as well. • However, data streams have other methods that allow them to read and write primitive type.
  • 40. Jan. 2004 40 Writing to Data Output Streams import java.io.*; class DataOutputStreamDemo { public static void main(String args[]) { try {//Create a file output stream FileOutputStream fos = new FileOutputStream(args[0]); //Create a data output straem DataOutputStream dos = new DataOutputStream(fos); //Write various types of data to the file dos.writeBoolean(false); dos.writeByte(Byte.MAX_VALUE);
  • 41. Jan. 2004 41 Writing to Data Output Streams dos.writeChar(‘A’); dos.writeDouble(Double.MAX_VALUE); dos.writeFloat(Float. MAX_VALUE); dos.writeInt(int. MAX_VALUE); dos.writeLong(Long. MAX_VALUE); dos.writeShort(Short. MAX_VALUE); //Close file output stream fos.close(); }catch(Exception e) {System.out.println(“Exception: ” + e);} }}
  • 42. Jan. 2004 42 Print Streams • Allows very simple printing of both primitive values, objects, string literals. • There are many overloaded print( ) and println( ) methods. • This method is deprecated in Java 1.1. • The biggest problem with this class is that it does not properly handle international character sets. • Use the PrintWriter class instead.
  • 43. Jan. 2004 43 Readers and Writers • Classes that read and write character based data. • These characters can have varying widths depending on the character set being used. • Readers and writers know how to handle many different character sets.
  • 44. Jan. 2004 44 Reader Class • java.io.Reader • This class is deliberately similar to the java.io.InputStream class. • Methods in the Reader class are similar to the InputStream class except that the methods work on characters not bytes.
  • 45. Jan. 2004 45 Writer Class • Java.io.Writer • This class is similar to the java.io.OutputStream class. • Methods in the Writer class now work on characters and not bytes.
  • 46. Jan. 2004 46 InputStreamReader • java. io.InputStreamReader acts as a translater between byte streams and character streams. • It reads bytes from the input stream and translates them into characters according to a specified character encoding.
  • 47. Jan. 2004 47 InputStreamReader Class • You can set the encoding scheme or you can use the platforms default setting. • public InputstreamReader(Inputstream in) • public InputStreamReader(InputStream in, String enc) throws UnsupportedEncoding Exception
  • 48. Jan. 2004 48 OutputStreamWriter • java. io.OutputStreamWriter will write bytes of data to the output stream after translating the characters according to the specified encoding. • public OutputStreamWriter(OutputStream out) • public OutputStreamWriter(OutputStream out, String enc) throws UnsupportedEncodingException
  • 49. Jan. 2004 49 Buffered Reads/Writes • There are classes that allow for a more efficient reading and writing of characters by buffering. • java.io.BufferedReader • java.io.BufferedWriter • These classes are similar to the Buffered Stream classes. • Most notable for the readLine() Method. This allows data to be read a line at a time. • public String readLine() throws IOException
  • 50. Jan. 2004 50 Buffered Reads/Writes import java.io.*; public class StringInputFile { public static void main(String[] arg) throws Exception { PrintStream backup; FileOutputStream backupFileStream; File backupFile; backupFile = new File(“backup”); backupFileStream = new FileOutputStream(backupFile); backup = new PrintStream(backupFileStream);
  • 51. Jan. 2004 51 System.out.println(“This is my first data file”); backup.println(“This is my first data file”); System.out.println(“... but it won't be my last”); backup.println(“... but it won’t be my last”); } } Buffered Reads/Writes
  • 52. Jan. 2004 52 Writing output to a file involves three steps as follows: • Create an File object • Create an FileOutputStream object • Create a PrintStream object Buffered Reads/Writes
  • 53. Jan. 2004 53 Buffered Reads/Writes import java.io.*; public class StringInputFile { public static void main(String[] arg) throws Exception { InputStreamReader backup; BufferedReader br; FileInputStream backupFileStream; File backupFile; String inputline;
  • 54. Jan. 2004 54 backupFile = new File(“backup”); backupFileStream = new FileInputStream(backupFile); backup = new InputStreamReader(backupFileStream); br = new BufferedReader(backup); inputline = br.readLine(); System.out.println(inputline); inputline = br.readLine(); System.out.println(inputline); } } Buffered Reads/Writes
  • 55. Jan. 2004 55 Reading data from a file involves three steps as follows: • Create an FileInputStream or BufferedInputStream object • Create an InputStreamReader object which we use to • Create a BufferedReader object Buffered Reads/Writes
  • 56. Jan. 2004 56 Example: Send Data(l) import java.net.*; import java.io.*; public class SendData extends Thread { Socket sock; public SendData (Socket sock) { this.sock = sock; }//SendData constructor public void run() { string line;
  • 57. Jan. 2004 57 Example: Send Data(2) try { OutputStreamWriter outw=new outputstreamwriter(sock.getOutputStream()); BufferedWriter sockout=new BufferedWriter(outw); InputStreamReader inr = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(inr); while ((line = in.readLine()) != null) { sockout.write(line+ “n”);
  • 58. Jan. 2004 58 Example: Send Data(3) sockout.flush(); yield( ); }//while } //try catch (java.io.IoException e) { System.out.println(e); System.exit(0); }//catch } //run }//SendData
  • 59. Jan. 2004 59 Example: Receive Data(l) import java.net.*; import java.io.*; public class RcveData extends Thread { Socket sock; public RcveData(Socket sock) { this.sock = sock; } public void run() { String line;
  • 60. Jan. 2004 60 Example: Receive Data(2) try { InputStreamReader inr = new InputStreamReader(sock.getlnputStream()); BufferedReader in = new BufferedReader(inr); while ((line = in.readLine()) != null) { System.out.print(mReceiving: System.out.println(line); yield(); }//while )//try
  • 61. Jan. 2004 61 Example: Receive Data(3) catch (java.io.IOException e) { System.out.println(e); System.exit(0); I }//catch }//run }//RCVeData