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

IO Java Unit 2

The document discusses input/output streams in Java. It describes different types of streams like byte streams, character streams, and file streams. It explains how to read from and write to the console and files using classes like BufferedReader, PrintWriter, FileInputStream and FileOutputStream.

Uploaded by

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

IO Java Unit 2

The document discusses input/output streams in Java. It describes different types of streams like byte streams, character streams, and file streams. It explains how to read from and write to the console and files using classes like BufferedReader, PrintWriter, FileInputStream and FileOutputStream.

Uploaded by

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

IO

Overview of I/O Streams

To bring in information, a program opens a


stream on an information source (a file,
memory, a socket) and reads the information
sequentially, as shown in the following figure.
Overview of I/O STREAMS Contd.

Similarly, a program can send information to


an external destination by opening a stream to
a destination and writing the information out
sequentially, as shown in the following figure.
Overview of I/O streams Contd..

• The java.io package contains a collection of


stream classes that support algorithms for
reading and writing. To use these classes, a
program needs to import the java.io package.
• The stream classes are divided into two class
hierarchies, based on the data type (either
characters or bytes) on which they operate i.e
Character Stream and Byte Stream
Files and Streams
• File streams
– Byte-based streams – stores data in binary format
• Binary files – created from byte-based streams, read by a program that converts
data to human-readable format
– Character-based streams – stores data as a sequence of characters
• Text files – created from character-based streams, can be read by text editors
• Java opens file by creating an object and associating a stream with it
• Standard streams – each stream can be redirected
– System.in – standard input stream object, can be redirected with method
setIn
– System.out – standard output stream object, can be redirected with
method setOut
– System.err – standard error stream object, can be redirected with method
setErr

5
System
• Java.lang package defines a class called System, which encapsulates
several aspects of the run-time environment.
• System also contains three predefined stream variables: in, out,
and err.
• These fields are declared as public, static, and final within System.
This means that they can be used by any other part of your
program and without reference to a specific System object.
• System.out refers to the standard output stream. By default, this is
the console.
• System.in refers to standard input, which is the keyboard by
default.
• System.err refers to the standard error stream, which also is the
console by default.
• However, these streams may be redirected to any compatible I/O
device.
Reading Console Input
The following line of code creates a
BufferedReader that is connected to the
keyboard:
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
• After this statement executes, br is a
character-based stream that is linked to the
console through System.in.
Buffered reader example
// Use a BufferedReader to read characters from the console.
import java.io.*;
class BRRead {
public static void main(String args[]) throws IOException
{
char c;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
// read characters
Here is a sample run:
do { Enter characters, 'q' to quit.
c = (char) br.read(); 123abcq
System.out.println(c); 1
} while(c != 'q'); 2
3
}
a
} b
c
q
Reading strings
// Read a string from console using a BufferedReader.
import java.io.*;
class BRReadLines {
public static void main(String args[]) throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
do {
str = br.readLine();
System.out.println(str);
} while(!str.equals("stop"));
}
}
Writing Console Output
• Here is a short example that uses write( ) to output the
character "A" followed by a newline to the screen:
class WriteDemo {
public static void main(String args[]) {
int b;
b = 'A';
System.out.write(b);
System.out.write('\n');
}
}
PrintWriter
• PrintWriter is one of the character-based
classes.
• Using a character-based class for console
output makes internationalizing your program
easier.
• PrintWriter defines several constructors. The
one we will use is shown here:
PrintWriter(OutputStream outputStream,
boolean flushingOn) True – flushing is done
automatically
False- flushing is not
automatic
PrintWriterDemo
// Demonstrate PrintWriter
import java.io.*;
public class PrintWriterDemo {
public static void main(String args[]) {
PrintWriter pw = new PrintWriter(System.out, true);
pw.println("This is a string");
int i = -7; Uses print() nad println() methods just like
System.in
pw.println(i);
double d = 4.5e-7;
pw.println(d);
The output from this program is shown here:
} This is a string
} -7
4.5E-7
Reading and Writing Files
• FileInputStream(String fileName) throws
FileNotFoundException
• FileOutputStream(String fileName) throws
FileNotFoundException
Reading and Writing Files
import java.io.*; try {
class ShowFile { do {
public static void main(String args[]) i = fin.read();
{ if(i != -1) System.out.print((char) i);
int i; } while(i != -1);
FileInputStream fin; } catch(IOException e) {
// First, confirm that a filename has been System.out.println("Error Reading File");
specified. }
if(args.length != 1) { // Close the file.
System.out.println("Usage: ShowFile try {
filename"); fin.close();
return; } catch(IOException e) {
} System.out.println("Error Closing File");
// Attempt to open the file. }
try { }
fin = new FileInputStream(args[0]); }
} catch(FileNotFoundException e) {
System.out.println("Cannot Open File");
return; java ShowFile TEST.TXT
}
// At this point, the file is open and can be
read.
// The following reads characters until EOF is
encountered.
Single catch statement and closing of
file in finally -block
try {
fin = new FileInputStream(args[0]);
do {
i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);
} catch(IOException e) {
System.out.println("I/O Error: " + e);
} finally {
// Close file in all cases.
try {
if(fin != null) fin.close();
} catch(IOException e) {
System.out.println("Error Closing File");
}
}
Copy a File
import java.io.*; do {
class CopyFile { i = fin.read();
public static void main(String args[]) if(i != -1) fout.write(i);
throws IOException } while(i != -1);
{ } catch(IOException e) {
int i; System.out.println("I/O Error: " + e);
FileInputStream fin = null; } finally {
FileOutputStream fout = null; try {
// First, confirm that both files have been if(fin != null) fin.close();
specified. } catch(IOException e2) {
if(args.length != 2) { System.out.println("Error Closing Input
System.out.println("Usage: CopyFile from File");
to"); }
return; try {
} if(fout != null) fout.close();
// Copy a File. } catch(IOException e2) {
try { System.out.println("Error Closing Output
// Attempt to open the files. File");
fin = new FileInputStream(args[0]); }
fout = new FileOutputStream(args[1]); }
}
}
Automatically Closing a File
try (resource-specification) {
// use the resource
}
Automatically closing a file
import java.io.*;
class ShowFile {
public static void main(String args[])
{
int i;
if(args.length != 1) {
System.out.println("Usage: ShowFile filename");
return;
}
try(FileInputStream fin = new FileInputStream(args[0])) {
do {
i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);
} catch(FileNotFoundException e) {
System.out.println("File Not Found.");
} catch(IOException e) {
System.out.println("An I/O Error Occurred");
}
}
}
File class
• File(String directoryPath)
• File(String directoryPath, String filename)
• File(File dirObj, String filename)

• File f1 = new File("/");


• File f2 = new File("/","autoexec.bat");
• File f3 = new File(f1,"autoexec.bat");
FILE Class
import java.io.File; p(f1.canWrite() ? "is
class FileDemo { writeable" : "is not writeable");
static void p(String s) { p(f1.canRead() ? "is readable"
System.out.println(s); : "is not readable");
} p("is " + (f1.isDirectory() ? "" :
public static void main(String args[]) { "not" + " a directory"));
File f1 = new p(f1.isFile() ? "is normal file" :
File("/java/COPYRIGHT"); "might be a named pipe");
p("File Name: " + f1.getName()); p(f1.isAbsolute() ? "is
absolute" : "is not absolute");
p("Path: " + f1.getPath());
p("File last modified: " +
p("Abs Path: " + f1.lastModified());
f1.getAbsolutePath());
p("File size: " + f1.length() + "
p("Parent: " + f1.getParent()); Bytes");
p(f1.exists() ? "exists" : "does not }
exist");
}
Output
• File Name: COPYRIGHT
• Path: \java\COPYRIGHT
• Abs Path: C:\java\COPYRIGHT
• Parent: \java
• exists
• is writeable
• is readable
• is not a directory
• is normal file
• is not absolute
• File last modified: 1282832030047
• File size: 695 Bytes
Other file functions
• isFile( ) returns true if called on a file and false if called on a
directory. Also, isFile( ) returns false for some special files, such
as device drivers and named pipes, so this method can be used
to make sure the file will behave as a file.
• The isAbsolute( ) method returns true if the file has an absolute
path and false if its path is relative.
boolean renameTo(File newName)
• Here, the filename specified by newName becomes the new
name of the invoking File object. It will return true upon
success and false if the file cannot be renamed (if you attempt
to rename a file so that it uses an existing filename, for
example).
• delete( ), which deletes the disk file represented by thepath of
the invoking File object. It is shown here:
boolean delete( )
• You can also use delete( ) to delete a directory if the directory is
empty. delete( ) returns true if it deletes the file and false if the
file cannot be removed.
Java NIO
• NIO was created to allow Java programmers to
implement high-speed I/O without having to
write custom native code.
• NIO moves the most time-consuming I/O
activities (namely, filling and draining buffers)
back into the operating system, thus allowing
for a great increase in speed.
Java NIO
• Java NIO fundamental components are given
below:
• Channels and Buffers: In standard I/O API the
character streams and byte streams are used.
• In NIO we work with channels and buffers. Data is
always written from a buffer to a channel and
read from a channel to a buffer.
• Selectors: Java NIO provides the concept of
"selectors". It is an object that can be used for
monitoring the multiple channels for events like
data arrived, connection opened etc. Therefore
single thread can monitor the multiple channels
for data.
• Non-blocking I/O: Java NIO provides the feature
of Non-blocking I/O.
JAVA NIO Vs IO
Difference between NIO & IO
IO NIO
Stream Oriented Buffer Oriented
Blocking IO Non-Blocking IO
Selectors

The NIO system is built on two foundational items: buffers and channels. A buffer holds
data. A channel represents an open connection to an I/O device, such as a file or a socket.
In general, to use the NIO system, you obtain a channel to an I/O device and a buffer to
hold data
IO Vs NIO
• IO – Stream oriented means - read one or more
bytes at a time, from a stream
• Not cached
• Cannot move back and forth in the data

• NIO works with channels and buffers


• NIO – Buffer oriented
• Data read from buffer to channel and from a
channel to buffer
• Can move back and forth - flexibility
Blocking Vs Non-Blocking I/O
• IO- Blocking Mode
– When a read() or Write() is invoked, corresponding
thread gets blocked until that respective operation
is complete

• NIO – Non-Blocking Mode


– Requests reading of data from a channel, at the
same time the thread can so some other activity
until the data arrives
– Thread can spend idle time on other channels
Java NIO – Selector
• single thread to monitor multiple channels of
input
• an object that can be used for monitoring the
multiple channels for events like data arrived,
connection opened etc
• "select" the channels – either for read or
write
NIO2
• extended NIO that offers further new file
system APIs, called NIO2 released with Java SE
7
• NIO2 provides two major methods of reading
a file:
– Using buffer and channel classes
– Using Path and Files classes
NIO Enhancements
• Path Interface - encapsulates a path to a file.
• glue that binds together many of the NIO.2 file-
based features.
• describes a file’s location within the directory
structure

• File Class – Static methods to perform actions on


the file
• Files have methods that let you copy or move files.
• Methods - isExecutable, isHidden ,isReadable
Using NIO for channel based I/O
• obtain a Path to the file using Paths.get()
• SeekableByteChannel is an interface that
describes a channel that can be used for file
operations.
– Example channelRead.java
Write into file
• Write into file using static SeekableByteChannel
newByteChannel(Path path, OpenOption ...
how) throws IOException
• How parameter - must specify
StandardOpenOption.WRITE.
• If you want to create the file if it does not
already exist, then you must also specify
StandardOpenOption.CREATE.
- ChannelWrite.java
Change notifiers
• polling was typically the best way to detect
change events.

You might also like