Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 38

CHAPTER 5 :

INPUT/OUTPUT
STREAM
ADVANCED OBJECT–ORIENTED PROGRAMMING
WHAT IS I/O STREAM
■ In general, a stream means continuous flow of data
■ A Stream is linked to a physical layer by java I/O system to make input and output
operation in java.
■ Java encapsulates Stream under java.io package. Java defines two types of streams. They
are,
– Byte Stream : It provides a convenient means for handling input and output of byte.
– Character Stream : It provides a convenient means for handling input and output of
characters. Character stream uses Unicode and therefore can be internationalized.

Stream – A sequence of data.


Input Stream: reads data from source.
Output Stream: writes data to destination.
.

I/0 CLASS HIERARCHY

Byte-oriented streams
• Intended for general-purpose input and output.
• Data may be primitive data types or raw bytes.

Character-oriented streams https://


• Intended for character data. www.developer.com/java/data/streamline-your-understanding-
• Data is transformed from/to 16 bit Java used f-the-java-io-stream.html
inside programs to the UTF format used
externally.
https://www.informit.com/articles/article.aspx?p=26067
.

BYTE STREAM CLASSES


Byte stream is defined by using two abstract class at the top of hierarchy
 InputStream and OutputStream
Some important Byte stream classes.
Stream class Description
BufferedInputStream Used for Buffered Input Stream.

BufferedOutputStrea Used for Buffered Output Stream.


m
DataInputStream Contains method for reading java
standard datatype
DataOutputStream An output stream that contain
The InputStream and OutputStream classes
method for writing java standard
data type
(abstract) are the super classes of all the
FileInputStream Input stream that reads from a file
input/output stream classes: 
FileOutputStream Output stream that write to a file.
These classes define several key methods.
InputStream Abstract class that describe stream
input. Two most important are
OutputStream Abstract class that describe stream 1.read() : reads byte of data.
output.
PrintStream Output Stream that
2.write() : Writes byte of data.
contain print() and println()method
BYTE STREAM CLASSES
.

InputStream OutputStream
FIleInputStream FileOutputStream
ByteArrayInputStream ByteArrayOutputStream
ObjectInputStream ObjectOutputStream
PipedInputStream PipedOutputStream
FilteredInputStream FilteredOutputStream
BufferedInputStream BufferedOutputStream
DataInputStream DataOutputStream
BYTE STREAM CLASSES .

import java.io.File; Reads data from a particular file using


import java.io.FileInputStream; FileInputStream and writes it to
import java.io.FileOutputStream; another, using FileOutputStream.
import java.io.IOException;
public class IOStreamsExample {
public static void main(String args[]) throws IOException {
//Creating FileInputStream object
File file = new File("D:/myFile.txt");
FileInputStream fis = new FileInputStream(file);
byte bytes[] = new byte[(int) file.length()];
//Reading data from the file Output
fis.read(bytes); Data successfully written in the specified file
//Writing data to another file
File out = new File("D:/CopyOfmyFile.txt");
FileOutputStream outputStream = new FileOutputStream(out);
//Writing data to the file
outputStream.write(bytes);
outputStream.flush();
System.out.println("Data successfully written in the specified file");
}
}
.

DETERMINE FILE LENGTH

Java File length() method returns the file size in bytes. The return value is unspecified if this file denotes a directory. Make sure file exists and
it’s not a directory.
.

InputStream Classes
• It is an abstract class. The superclass of all classes representing an input stream of bytes .
public abstract class InputStream
extends Object
implements Closeable
Modifier and Type Method and Description
int available()Returns an estimate of the number of bytes that can be read (or skipped over)
from this input stream without blocking by the next invocation of a method for this input
stream.
void close()Closes this input stream and releases any system resources associated with the stream.
void mark(int readlimit)Marks the current position in this input stream.
boolean markSupported()Tests if this input stream supports the mark and resetmethods.
abstract int read()Reads the next byte of data from the input stream.
int read(byte[] b)Reads some number of bytes from the input stream and stores them into the
buffer array b.
int read(byte[] b, int off, int len)Reads up to len bytes of data from the input stream into an
array of bytes.
void reset()Repositions this stream to the position at the time the markmethod was last called on
this input stream.
long skip(long n)Skips over and discards n bytes of data from this input stream.
OutputStream Classes
.

• It is an abstract class. The superclass of all classes representing an output stream of bytes . An
output stream accepts output bytes and sends them to sink. Applications that need to define a
subclass of OutputStream must always provide at least a method that writes one byte of
output.
public abstract class OutputStream
extends Object
implements Closeable, Flushable

Modifier and Type Method and Description


void close()Closes this output stream and releases any system
resources associated with this stream.

void flush()Flushes this output stream and forces any buffered output
bytes to be written out.
void write(byte[] b)Writes b.length bytes from the specified byte
array to this output stream.
void write(byte[] b, int off, int len)Writes len bytes from the specified
byte array starting at offset off to this output stream.

abstract void write(int b)Writes the specified byte to this output stream.


Class FileCopyUtil
.

• There is no internal java class/method to copy a file.


java.lang.Object
oracle.ide.util.FileCopyUtil

public class FileCopyUtil
extends java.lang.Objec

Method Summary
static void copyDir(java.io.File src, java.io.File target, boolean recurse, boolean overwrite) 
          Copies all files from src to target.
static void copyDir(java.lang.String src, java.lang.String target, boolean recurse, boolean overwrite) 
          Copies all files from src to target.
static void copyFile(java.io.File src, java.io.File target, boolean overwrite) 
          Copies one file (src) to target.
static void copyFile(java.lang.String src, java.lang.String target, boolean overwrite) 
          Copies one file (src) to target.
static void main(java.lang.String[] args) 
          Test
.

Class FileCopyUtil
1. copyFile (Use File object)
public static void copyFile(java.io.File src,
java.io.File target,
boolean overwrite)
throws java.io.IOException
Copies one file (src) to target. This version takes File objects.
Parameters:
src - Source file
target - Desired destination file
overwrite - If the file exists, should it be overwritten
Throws:
java.io.IOException
.

Class FileCopyUtil
2. copyFile (Use String object)
public static void copyFile(java.lang.String src,
java. lang.String target,
boolean overwrite)
throws java.io.IOException
Copies one file (src) to target. This version takes String objects.
Parameters:
src - Source file
target - Desired targetination file
overwrite - If the file exists, should it be overwritten
Throws:
java.io.IOException
.

Class FileCopyUtil
1. copyDir (Use File object)
public static void copyDir(java.io.File src,
java.io.File target,
boolean recurse,
boolean overwrite)
throws java.io.IOException
Copies one file from src to target. This version takes File objects.
Parameters:
src - Source directory
target - targetination directory
recurse – Recurse through sub dirstories or folders
overwrite - If the file exists, should it be overwritten
Throws:
java.io.IOException
.

Class FileCopyUtil
2. copyDir (Use String object)
public static void copyFile(java.lang.String src,
java. lang.String target,
boolean recurse.
boolean overwrite)
throws java.io.IOException
Copies one file (src) to target. This version takes String objects.
Parameters:
src - Source file
target - Desired targetination file
recurse – Recurse through sub directories or folders
overwrite - If the file exists, should it be overwritten
Throws:
java.io.IOException
.

CHARACTER STREAM CLASSES


• Character stream is also defined by using two abstract classes at the top of
hierarchy, they are Reader and Writer.
• These two abstract classes have several concrete classes that handle unicode character.

Some important Charcter stream classes

Stream class Description


BufferedReader Handles buffered input stream.

BufferedWriter Handles buffered output stream.

FileReader Input stream that reads from file.

FileWriter Output stream that writes to file.

InputStreamReader Input stream that translate byte to character

OutputStreamReader Output stream that translate character to byte.

PrintWriter Output Stream that contain print() and println()method.

Reader Abstract class that define character stream input

Writer Abstract class that define character stream output


.

File Viewer Utility


• Character stream is also defined by using two abstract class at the top of
hierarchy, they are Reader and Writer.
• These two abstract classes have several concrete classes that handle unicode character.
.

Buffered Readers/Writers
• BufferedReader and BufferedWriter use an internal buffer to store data while
reading and writing, respectively. BufferedReader provides a new
method readLine(), which reads a line and returns a String (without the line
delimiter). 
• BufferedReader class is used to read the text from a character-based input stream. It can be
used to read data line by line by readLine() method. It makes the performance fast(why). It
inherits Reader class.

• public class BufferedReader extends Reader 

• Example1

• Example2
.

Buffered Readers/Writers
Reading   data from the text file testout.txt
package com.javatpoint;  
import java.io.*;  
public class BufferedReaderExample {  
    public static void main(String args[])throws Exception{    
          FileReader fr=new FileReader("D:\\testout.txt");    
          BufferedReader br=new BufferedReader(fr);    
  
          int i;    
          while((i=br.read())!=-1){  
          System.out.print((char)i);  
          }   assuming that you have following data in "testout.txt" file:
          br.close();    
Welcome to javaTpoint.
          fr.close();    
Output:
    }     Welcome to javaTpoint.

.

Buffered Readers/Writers
Reading data from console - reading the line by line data from the keyboard.

package com.javatpoint;  
import java.io.*;  
public class BufferedReaderExample{    
public static void main(String args[])throws Exception{             
    InputStreamReader r=new InputStreamReader(System.in);    
    BufferedReader br=new BufferedReader(r);            
    System.out.println("Enter your name");    
    String name=br.readLine();    
    System.out.println("Welcome "+name);     Output:
}     Enter your name
}  Wan Asiah
Welcome Wan Asiah
.

Binary Versus Character Streams


Byte Stream import java.io.*;   
Byte streams process data byte public class BStream
by byte (8 bits). For example {  public static void main(String[] args) throws IOException
FileInputStream is used to read     {  FileInputStream sourceStream = null;
from source and         FileOutputStream targetStream = null;
FileOutputStream to write to the           try 
destination.         {   sourceStream = new FileInputStream("sorcefile.txt");
            targetStream = new FileOutputStream ("targetfile.txt");
            // Reading source file and writing content to target
            // file byte by byte
            int temp;
            while ((temp = sourceStream.read()) != -1)
                targetStream.write((byte)temp);            
        }
        finally 
        {   if (sourceStream != null)
                sourceStream.close();            
            if (targetStream != null)            
                targetStream.close();            
        }
    }
}
Binary Versus Character Streams
.

Character Stream // Java Program illustrating that we can read a file in


 characters are stored using // a human readable format using FileReader
Unicode conventions (Refer this import java.io.*;   // Accessing FileReader, FileWriter, IOException
 for details). Character stream public class GfG
automatically allows us to {   public static void main(String[] args) throws IOException
read/write data character by     { FileReader sourceStream = null;
character. For example         try   {
FileReader and FileWriter are            sourceStream = new FileReader("test.txt");
character streams used to read             // Reading sourcefile and writing content to 
from source and write to             // target file character by character. 
destination.             int temp;
            while ((temp = sourceStream.read()) != -1)
                 System.out.println((char)temp);
        }
        finally 
        {            
            // Closing stream as no longer in use 
            if (sourceStream != null)            
                sourceStream.close();         
        }     }
} Output :
Shows contents of file test.txt
.

Binary Versus Character Streams

• Names of character streams typically end with Reader/Writer and names of


byte streams end with InputStream/OutputStream
• It is always recommended to close the stream if it is no longer in use. This
ensures that the streams won’t be affected if any error occurs.
• The above codes may not run in online compilers as files may not exist.
• Byte oriented reads byte by byte.  A byte stream is suitable for processing raw data
like binary files.
• Character stream is useful when we want to process text files. character size is
typically 16 bits.
instance of a lower level stream.
CHAINING STREAMS
. 1. This means that an instance of one Stream is passed as a paramete
A good example of a chained stream is the InputStreamReader class, which is what we oftalked
constructor another. about in my previous
article.
This class leverages chaining by providing reader behavior over an  InputStream. It translates the binary response to
The FileOutputStream class deals with the actual business of opening a
character behavior. writing and the OutputStreamWriter deals writing to the file. The
Let us see how it works. OutputStreamWriter class was added with the JDK 1.1 and can take a
constructor
void doChain(InputStream in) throws IOException{ int length; char[] buffer = new char[128]; try(InputStreamReader rdr that takes a String
= new InputStreamReader(in)) to allow for=handling
{ while((length character
rdr.read(buffer)) >= 0)sets apart
{ //do
something } } } the current default. This way you can process files that contain Unicode
character sets such as Chinese or Cyrilic. The writer classes understand
idea of data as text rather than simply as a sequence of bytes that might
numbers or anything at all.
As you can see, we do not need to care about how the  InputStream works. Whether
Note that the File
it is backed by aclass
file oris a bit misleading
network, as you might expect it exclusi
it does not matter.
refer to an actual file and to be concerned with writing to and from a phy
The only
import thing we know that it gives us binary data, we will pass itfile.
java.io.*; toByour  usingInputStreamReader
Stream chaining  andyou itcanconverts
assemble fileitprocessing
and canfunctio
work with
public it asStio
class a character
{ data. from multiple classes, rather than needing a huge range of discreet file
public static void main(String argv[]){ processing classes.
Notice that we use try-with-resources here as well. If we close the InputStreamReader, it automatically closes theInputStream as well. This a very powerful concept, that you should know about.
try{ File f = new File("Output.txt");
FileOutputStream fos= new FileOutputStream(f); 2. Both byte stream and character stream h
OutputStreamWriter out = new
low-level high level streams.
OutputStreamWriter(fos);
out.write("Hello World");
out.close(); eg: high-level - FilterInputStream and 
} FilterOutputStream
catch(Exception e){}
}
} 2. high-level Sub classes of 
FilterInputStream and 
FilterOutputStreamare known as high-
level streams.

3. There are four high-level streams on inp


RULES OF CHAINING
.

• One stream can be linked or chained to another, but obeying some simple rules.
The output of one stream becomes input to the other. It means, we pass an object
of one stream as parameter to another stream constructor; this is how chaining is
affected.

• Rules in chaining:
1. The input for a high-level stream may come from a low-level stream or
another high-level stream. That is, the constructor of a high-level stream can
be passed with an object of low-level or high-level.

2. Being low-level, the low-level stream should work by itself. It is not entitled
to get passed with any other stream.

• the low-level stream opens the file and hand it over (passes) to a high-level
stream. High-level stream cannot open a file directly. That is, high-level streams
just add extra functionality and depend solely on low-level streams.
RULES OF CHAINING - EXAMPLES
.

tring str1 = "Accept\ngreetings\nfrom\nway2.java";


StringBufferInputStream sbi = new StringBufferInputStream(str1); // low-level
LineNumberInputStream lis = new LineNumberInputStream(sbi); // high-level
DataInputStream dis = new DataInputStream(lis); // high-level

The intention of code is to give line numbers to the words of string str1 separated by \n. This string is passed
to the constructor of low-level StringBufferInputStream because StringBufferInputStream can hold a string.
The sbi object is passed to the constructor of high-level LineNumberInputStream to give line numbers. Again,
the lis object is passed to another high-level stream constructor DataInputStream which can read each line
separately.

Here, the functionalities achieved with different streams chained are


1.Low-level FileInputStream opens the file.
2.High-level LineNumberInputStream adds line numbers.
3.High-level DataInputStream reads line by line.
The Line Count Program
.

• We can read lines in a file using BufferedReader class 


data.txt
import java.io.BufferedReader; public static int getLineCount() throws IOException {
import java.io.File; int lineCount = 0; This is Line 1
import java.io.FileInputStream; String data;
import java.io.FileNotFoundException; while((data = reader.readLine()) != null) { This is Line 2
import java.io.IOException; lineCount++;
import java.io.InputStreamReader; This is Line 3
}
return lineCount; This is Line 4
public class Tester {
}
private static final String FILE_PATH = "data.txt"; } This is Line 5
public static void main(String args[]) throws IOException {
This is Line 6
FileUtil fileUtil = new FileUtil(FILE_PATH);
System.out.println("No. of lines in file: " + fileUtil.getLineCount());
This is Line 7
}
} This is Line 8
class FileUtil {
static BufferedReader reader = null; This is Line 9
public FileUtil(String filePath) throws FileNotFoundException {
File file = new File(filePath); This is Line 10
FileInputStream fileStream = new FileInputStream(file);
InputStreamReader input = new InputStreamReader(fileStream);
reader = new BufferedReader(input);
}
.

The File Concatenation


• to merge multiple files into one in.

• We can append to file in java using following classes :

1. Java append to file using FileWriter


2. ava append content to existing file using BufferedWriter
3. Append text to file in java using PrintWriter
4. Append to file in java using FileOutputStream
.

The File Concatenation

Java append to file using FileWriter

File file = new File("append.txt");


FileWriter fr = new FileWriter(file, true);
fr.write("data");
fr.close();
.

The File Concatenation

Java append content to existing file using BufferedWriter

File file = new File("append.txt");


FileWriter fr = new FileWriter(file, true);
BufferedWriter br = new BufferedWriter(fr);
br.write("data");
br.close();
fr.close();
. using PrintWriter
Append text to file in java

The File Concatenation

Append text to file in java using PrintWriter

File file = new File("append.txt");


FileWriter fr = new FileWriter(file, true);
BufferedWriter br = new BufferedWriter(fr);
PrintWriter pr = new PrintWriter(br);
pr.println("data");
pr.close();
br.close();
fr.close();
.
. The File Concatenation

Append to file in java using FileOutputStream

You should use FileOutputStream to append data to file when it’s raw data, binary data, images, videos etc.

OutputStream os = new FileOutputStream(new File("append.txt"), true);


os.write("data".getBytes(), 0, "data".length());
os.close();
.
. The File Concatenation examples
import java.io.*;
class SequenceBuffer
{
public static void main(String[] args)
{
try{
FileInputStream file1 = new FileInputStream(\"dataFile1.txt\");
FileInputStream file2 = new FileInputStream(\"dataFile2.txt\");
SequenceInputStream resultFile = null;
resultFile = new SequenceInputStream(file1,file2);
BufferedInputStream inBuffer =
new BufferedInputStream(resultFile);
BufferedOutputStream outBuffer =
new BufferedOutputStream(System.out);
int ch;
while((ch = inBuffer.read())!=1){
outBuffer.write((char)ch);
}
inBuffer.close();
outBuffer.close();
file1.close();
file2.close();
}catch(Exception e) {}
}
}
.

ACCESSING THE HOST FILE SYSTEM


The hosts file is a computer file used in an operating system to map
hostnames to IP addresses. The hosts file is a plain-text file and is
traditionally named hosts.

hosts file is actually a plain text file that contains a local Domain name mapping table. It contains ip-addresses and
corresponding domain names. And this file has a greater priority than the external DNS servers. So when you enter a
domain in your browser, first your hosts file is consulted to check if you have a mapping for that domain, if so that
specified IP address is accessed, or else you go for the help of external domain name servers.

Your hosts file will be located in the following directory if you are running Windows.

C:\Windows\system32\drivers\etc\

127.0.0.1 refers to your local computer. Its is called as


the loop back address. So if you have any HTTP server
running in your computer that server will be accessed if
you go to 127.0.0.1. If you dont have a server in your
computer then you wont be taken to any webpage.
.

ACCESSING THE HOST FILE SYSTEM


What is hosts file and how to edit it
The hosts file is a computer file used in an operating system to map hostnames to IP addresses. The hosts
file is a plain-text file and is traditionally named hosts.

For various reasons it may be necessary to update the hosts file on your computer to properly resolve a web
site by its domain name. The most common reason for this is to allow people to view or publish web content
immediately after purchasing a new domain name or transferring an existing domain name to another ISP
(Internet Service Provider).
New and transferred domain names have a delay period that can be anywhere from a few hours to a few
days. During this period of time the new or transferred domain information propagates around the internet,
and is generally unavailable.
If you need to update your site immediately and cannot wait for the propagation of domain information
around the internet, you can edit a file on your computer as a temporary work around.

Please note: this work around is only valid on the computer/server on which the change was made. It will
not make the web site available to anyone on the internet.
.

ACCESSING THE HOST FILE SYSTEM


Windows operating systems contain a file called ‘hosts’ that will force resolution of your domain name.
1. Open the hosts file 
1. Go to the Start menu and choose Run. Type the following in the Run dialog box:
a. For Windows NT and Windows 2000:
C:\winnt\system32\drivers\etc
b. Windows XP, Windows Vista or Windows 7 
C:\Windows\System32\drivers\etc
2. Click the OK button (This should open a window with several files in it.)
3. Find the file called ‘hosts’ and double–click it. If prompted, specify that you would like to choose a
program to open the file with from a list of programs.
a. Choose ‘Notepad’ from the list of available programs.
2. Edit and save the hosts file 
1. Start typing on a new line at the bottom of the file. 
To do so, place your cursor at the very end of the last line and hit ‘Enter’ to start a new line.
2. Type these two lines of text like this example: 
(use your server IP address and your site domain in–place of the defaults below) 
a. 123.123.123.123 yourdomainname.com
b. 123.123.123.123 www.yourdomainname.com
3. Close the hosts file and save it when prompted.
3. Please note: At this point you should be able to view and publish to your web site using your domain name
on the computer where this change was made. 
.

The Directory Listing Program


• Character stream is also defined by using two abstract class at the top of
hierarchy, they are Reader and Writer.
• These two abstract classes have several concrete classes that handle unicode character.
.

Filtering The Directory Listing


• Character stream is also defined by using two abstract class at the top of
hierarchy, they are Reader and Writer.
• These two abstract classes have several concrete classes that handle unicode character.
.

READING /WRITING OBJECTS


• Character stream is also defined by using two abstract class at the top of
hierarchy, they are Reader and Writer.
• These two abstract classes have several concrete classes that handle unicode character.

You might also like