Professional Documents
Culture Documents
CH - 3 Part - 2 Stream
CH - 3 Part - 2 Stream
CH - 3 Part - 2 Stream
Stream
A stream of information
JAVA
SOURCE INFORMATION: READS
PROGRAM
A stream of information
JAVA DESTINATION
INFORMATION: WRITES
PROGRAM
Stream to make I/O operation fast.
Character Byte
Byte streams are used to perform input and output of 8-bit bytes.
Character streams are used to perform input and output for 16-bit
bytes
• Eg. FileReader and FileWriter classes
• System.out.println("simple message");
• //returns ASCII code of 1st character
• int i=System.in.read();
• System.err.println("error message");
Character Streams
Byte Streams
• Types : Input Stream and Output Stream
• Output Stream: write data to a destination, it may be a file, an array, peripheral device or socket.
• Input Stream: Read data from a source, it may be a file, an array, peripheral device or socket.
InputStream and OutputStream
SENDER
import java.net.*;
import java.io.*;
// import java.io.File;
// import java.io.FileInputStream;
// import java.io.IOException
// import java.io.BufferedInputStream;
// import java.io.DataInputStream;
public class Server {
// IOException − If an I/O error occurs.
public static void main (String [] args ) throws IOException {
// File Path
File transferFile = new File ("D:\\P2PFILE\\SENDER.txt");
// length of file in bytes is stored as int in bytearray
byte [] bytearray = new byte [(int)transferFile.length()];
// To read bytes from file
FileInputStream fin = new FileInputStream(transferFile);
// To read input as stream using internally created buffer array (many bytes at a time)
BufferedInputStream bin = new BufferedInputStream(fin);
/* Flush() - flushes this output stream and forces any buffered output bytes to be written
out. (file or console) */
os.flush();
// bytesRead contain the current statistics of the bytes read from the input ie inputstream,
int bytesRead;
// To read the data from the inputstream using the read method
// The data read from the input channel is stored in the byte array
bytesRead = is.read(bytearray,0,bytearray.length);
do {
// Read the bytes on the file
bytesRead = is.read(bytearray, currentTot, (bytearray.length-currentTot));
if(bytesRead >= 0)
currentTot += bytesRead;
} while(bytesRead > -1);