Chapter 5 - Java Io
Chapter 5 - Java Io
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.
Byte-oriented streams
• Intended for general-purpose input and output.
• Data may be primitive data types or raw bytes.
InputStream OutputStream
FIleInputStream FileOutputStream
ByteArrayInputStream ByteArrayOutputStrea
m
ObjectInputStream ObjectOutputStream
PipedInputStream PipedOutputStream
FilteredInputStream FilteredOutputStream
BufferedInputStream BufferedOutputStream
DataInputStream DataOutputStream
BYTE STREAM CLASSES .
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
Class FileCopyUtil
• There is no internal java class/method to copy a file.
java.lang.Object
oracle.ide.util.FileCopyUtil
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
import java.io.*;
public class Program {
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.
• 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{
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
.
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.
You should use FileOutputStream to append data to file when it’s raw data, binary data,
images, videos etc.
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\
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.
.