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 ByteArrayOutputStream
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 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
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.
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
.
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
.
• 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.
.