0% found this document useful (0 votes)
3 views

Chapter 5 - Java Io

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Chapter 5 - Java Io

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

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-und
• Data is transformed from/to 16 bit Java used erstanding-of-the-java-io-stream.html
inside programs to the UTF format used
externally.
https://www.informit.com/articles/article.aspx?
.

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


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

InputStream OutputStream
FIleInputStream FileOutputStream
ByteArrayInputStream ByteArrayOutputStrea
m
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()]; Output
//Reading data from the file Data successfully written in the
fis.read(bytes); 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");
.

BYTE STEAM CLASSES


import java.io.*;
public class Program {

public static void main(String args[]) throws


IOException {
FileInputStream in = null; The while loop reads data in the
FileOutputStream out = null; input.txt file and writes them in the new
file output.txt until reaching the end of
try {
in = new FileInputStream(“input.txt”); the file. The finally block will close the
out = new FileOutputStream(“output.txt”); files. Finally, the output.txt file will also
int c; have the same content as the input.txt
while ((c = in.read()) != -1) { file. Usually, it is possible to use Byte
out.write(c); Stream with any file type.
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
.

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 Method and Description
Type
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.
.

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 Method and Description


Type
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
.

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)
.

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
.

CHARACTER STREAM
import java.io.*;
public class Program {

public static void main(String args[]) throws IOException {


FileReader in = null;
FileWriter out = null;
Character stream in Java helps to
try { perform input and output for 16 bit
in = new FileReader(“input.txt”); Unicode. The most common classes for
out = new FileWriter(“output.txt”); character streaming in Java are
int c; FileReader and FileWriter. Internally,
while ((c = in.read()) != –1) { FileReader uses FileInputStream.
out.write(c);
} Similarly, the FileWrite uses
}finally { FileOutputStream.
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
.

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 public class BStream
data byte by byte (8 { public static void main(String[] args) throws IOException
bits). For example { FileInputStream sourceStream = null;
FileInputStream is used to FileOutputStream targetStream = null;
read from source and try
FileOutputStream to write { sourceStream = new FileInputStream("sorcefile.txt");
to the destination. 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 // a human readable format using FileReader
using Unicode import java.io.*; // Accessing FileReader, FileWriter, IOException
conventions (Refer this public class GfG
for details). Character { public static void main(String[] args) throws IOException
stream automatically { FileReader sourceStream = null;
allows us to read/write try {
data character by sourceStream = new FileReader("test.txt");
character. For example // Reading sourcefile and writing content to
FileReader and FileWriter // target file character by character.
are character streams int temp;
used to read from source while ((temp = sourceStream.read()) != -1)
and write to destination. 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
A good example of a chained stream is the InputStreamReader class, which is what weto talked
parameter about inof my
the constructor previous
another.
article.
This class leverages chaining by providing reader behavior over an InputStream. It translates the binary response to
character behavior. The FileOutputStream class deals with the actual busines
opening a file for writing and the OutputStreamWriter dea
Let us see how it works. writing to the file. The OutputStreamWriter class was add
void doChain(InputStream in) throws IOException{ int length; char[] buffer = new char[128]; try(InputStreamReader rdr =
with the JDK 1.1 and newtake
can InputStreamReader(in))
a constructor that takes a S
{ while((length = rdr.read(buffer)) >= 0) { //do something } } }
to allow for handling character sets apart from the curren
default. This way you can process files that contain Unico
character sets such as Chinese or Cyrilic. The writer class
understand the idea of data as text rather than simply as
As you can see, we do not need to care about how the InputStream works.sequence of bytes
Whether it is backed by a filethat might
or network, be
it does notnumbers
matter. or anything at
The only thing we know that it gives us binary data, we will pass itNote it
to that InputStreamReader
our
exclusively
the File class is aand
refer to an actual
bit misleading
itfileconverts
and to
asityou
be
andmight e
concerned w
import java.io.*;
can work with
public class Stio { it as a character data. writing to and from a physical file. By using Stream chain
Notice that
public we use
static void main(String
try-with-resources argv[]){
here as well.
you can assemble file processing functionality from multi
If we close the InputStreamReader, it automatically closes theInputStream as well. This a very powerful concept, that you should
knowtry{
about. File f = new File("Output.txt"); classes, rather than needing a huge range of discreet file
processing classes.
FileOutputStream fos= new FileOutputStream(f);
OutputStreamWriter out = new
OutputStreamWriter(fos); 2. Both byte stream and character stream h
out.write("Hello World"); low-level high level streams.
out.close();
}
catch(Exception e){} eg: high-level - FilterInputStream and
} FilterOutputStream
}
2. high-level Sub classes of
FilterInputStream and
FilterOutputStreamare known as high-
level streams.
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
import java.io.File; IOException { This is Line 1
import java.io.FileInputStream; int lineCount = 0;
import java.io.FileNotFoundException; String data; This is Line 2
import java.io.IOException; while((data = reader.readLine()) !=
import java.io.InputStreamReader; This is Line 3
null) {
public class Tester {
lineCount++; This is Line 4
}
return lineCount;
private static final String FILE_PATH = "data.txt"; This is Line 5
public static void main(String args[]) throws }
This is Line 6
IOException { }
FileUtil fileUtil = new FileUtil(FILE_PATH);
This is Line 7
System.out.println("No. of lines in file: " +
fileUtil.getLineCount()); This is Line 8
}
} This is Line 9
class FileUtil {
static BufferedReader reader = null; This is Line 10
public FileUtil(String filePath) throws
FileNotFoundException {
File file = new File(filePath);
FileInputStream fileStream = new
.

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();
Append text to file in java
. using PrintWriter

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
.

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