Unit IV Io1
Unit IV Io1
This work is created by N.Senthil madasamy, Dr. A.Noble Mary Juliet, Dr. M. Senthilkumar and is licensed under a
Creative Commons Attribution-ShareAlike 4.0 International License
Introduction
• Working with java.io.* package
• Operates with external data
• Data is retrieved from input Source
• Results are send to output Destination
• Sources and Destination devices:
– Network connection, memory buffer, or disk file
• These devices handles data as: Stream
Handling Files
• File class does not operate with input and
output streams
– i.e.., File class does not specify how
information is retrieved from or stored in
files
• File object only maintains:
– File permissions, time, date, and directory
path
Constructors in File
• File(String directoryPath)
• File(String directoryPath, String filename)
• File(File dirObj, String filename)
• File(URI uriObj)
f1.getName() COPYRIGHT.txt
f1.getPath() \java\COPYRIGHT.txt
f1.getAbsolutePath() C:\java\COPYRIGHT.txt
f1.getParent() \java
f1.exists() True
f1.canWrite() True
f1.canRead() True
f1.isDirectory() False
f1.isFile() True
f1.lastModified() 1282832030047
f1.length() 695 Bytes
Some other methods…
Directories
• A directory is a File that contains a list of other
files and directories
• Methods:
– boolean isDirectory( ) checks if the invoking
object is a directory
– String[ ] list( ) returns the names of all files and
directories inside the invoking directory
Write a java program to list only java files
import java.io.*;
class DirList1 {
public static void main(String args[])
{
String dirname = "G:/MCET/java/example";
File f1 = new File(dirname);
String s[] = f1.list();
for (int i=0; i < s.length; i++) {
if(s[i].endsWith(“java”)) System.out.println(s[i]);
}
}
Using Filename Filter
• Used to filter the list of files returned by list()
function
• Hence returning only those files that match a
certain filename pattern
String[ ] list(FilenameFilter FFObj)
• FilenameFilter A file interface
– Which calls:
boolean accept(File directory, String filename)
import java.io.*;
class DirList implements FilenameFilter{
String ext;
DirList(String s) { ext=s; }
public boolean accept(File dir, String name)
{ return name.endsWith(ext); }
public static void main(String args[])
{
String dirname = "G:/MCET/java/example";
File f1 = new File(dirname);
FilenameFilter only = new DirList("java");
String s[] = f1.list(only);
for (int i=0; i < s.length; i++) { System.out.println(s[i]);}
}
}
listFiles() method
• This method returns a list of “File” instances
inside a directory
• Constructors:
– File[ ] listFiles( )
– File[ ] listFiles(FilenameFilter FFObj)
– File[ ] listFiles(FileFilter FObj)
Creating Directories
• Methods used to create directories:
– mkdir( ) creates a directory, returning true on
success and false on failure
• False is returned if the path is not properly specified; or
path already exists
– mkdirs( ) creates a directory for which no path
exists
• Ie.., It creates both a directory and all the parents of
the directory
The Closeable and Flushable Interfaces
• Released in JDK 5
• They offer a uniform way of specifying that a
stream can be closed or flushed
• void close( )
– This method closes the invoking stream, releasing
any resources that it may hold
• void flush( )
– Force buffered output to be written to the stream
to which the object is attached
Stream
Stream
• A stream is an abstraction, which either produces or
consumes information
• A stream is a sequence of bytes that flows into or out of
your program.
• A stream is linked to a physical device by the Java I/O
system.
• The input stream gets input from a disk file, a keyboard
or a network socket.
• The output stream refers to the console, a disk file or a
network connection.
• To use stream classes, you must import java.io package.
Stream
Two types of streams:
• Byte Stream
• Character Stream
• Stream I/P and O/P methods generally permits
very small amounts of data (such as single char
or byte) to be written or read in a single
operation.
• Sending data transfers like this to a physical
device would be extremely inefficient.
• So a stream is often prepared with a “Buffer”,
and it is called a “Buffered Stream”.
• A buffer is simply a block of memory that is
used to batch up data transfers to or from an
external device.
Stream Input/Output operations:
• When you write data to a stream as a series of bytes
(i.e., binary data), it is written to the stream exactly
as it appears in memory.
• No transformations of the data take place.
Numerical values are just written as a series of
bytes.
• When you write data to a stream as a series of
characters, all numeric data is converted to a textual
representation before being written to the stream.
• This involves formatting the data to generate a
character representation of the data value.
Stream Input/Output operations:
ASCII representation of
characters
‘1’ ‘6’ ‘7’ ‘2’ ‘7’
Stream content
Ox31 Ox36 Ox37 Ox32 Ox37
class methods
Method Description
void write(int b) It writes the specified byte to the buffered output
stream.
void write(byte[] b, int off, int len) It write the bytes from the specified byte-input
stream into a specified byte array, starting with
the given offset
void flush() It flushes the buffered output stream.
BufferedInputStream Class
BufferedInputStream(InputStream IS)
int skipBytes(int x)
-Skips to byte n bytes
void readFully(byte[] b)
It is used to read input bytes and return an int value.
void readFully(byte[] b, int off, int len)
it is used to read len bytes from the input stream.
Example of DataOutputStream class
import java.io.*;
public class OutputExample {
public static void main(String[] args) throws IOException {
FileOutputStream file = new FileOutputStream(D:\\testout.txt);
DataOutputStream data = new DataOutputStream(file);
data.writeInt(65);
data.flush();
data.close();
System.out.println("Succcess...");
}
}
DataInputStream Class
import java.io.*;
public class DataStreamExample {
public static void main(String[] args) throws IOException {
InputStream input = new FileInputStream("D:\\testout.txt");
DataInputStream inst = new DataInputStream(input);
int count = input.available();
byte[] ary = new byte[count];
inst.read(ary);
for (int i=0;i<ary.length;i++) {
char k = (char) ary[i];
System.out.print(k);
}
PushbackInputStream
• The Java.io.PushbackInputStream class adds
functionality to another input stream, namely
the ability to "push back" or "unread" one
byte.
public class PushbackInputStream extends
FilterInputStream
Constructor
• PushbackInputStream(InputStream in)
– This creates a PushbackInputStream and saves its
argument, the input stream in, for later use.
• PushbackInputStream(InputStream in, int
size)
– This creates a PushbackInputStream with a
pushback buffer of the specified size, and saves its
argument, the input stream in, for later use.
• int available() This method 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() This method closes this input
stream and releases any system resources
associated with the stream.
• void mark(int readlimit) This method marks
the current position in this input stream.
• int read() This method reads the next byte of
data from this input stream.
• int read(byte[] b, int off, int len) This method
reads up to len bytes of data from this input
stream into an array of bytes.
• void reset() This method repositions this
stream to the position at the time the mark
method was last called on this input stream.
• long skip(long n) This method skips over and
discards n bytes of data from this input
stream.
•
EXAMPLE
PushbackInputStream input ;
Input = new PushbackInputStream(
new FileInputStream(“input.txt"));
int data = input.read();
The call to read() reads a byte just like
input.unread(data); from an InputStream.
Method Description
void print(char c) It prints the specified char value.
void println(char c)
import java.io.FileOutputStream;
import java.io.PrintStream;
public class PrintStreamTest{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt ");
PrintStream pout=new PrintStream(fout);
pout.println(2016);
pout.println("Hello Java");
pout.println("Welcome to Java");
pout.close();
fout.close();
System.out.println("Success?");
}
RandomAccessFile:
Methods:
• void seek( long newPosition) throws IOException;
– Used to set the current position of the file pointer.
– ‘newPosition’ specifies the new position (in bytes) of the
file pointer from the beginning of the file. After a call to
seek(), the next read/write operation will occur at the new
file position.
RandomAccessFile:
Methods:
• long getFilepointer()
– Return the current position of the file
pointer.
RandomAccessFile:
import java.io.*;
class RandomFileExample
{
public static void main(String[] args)
{
try
{
file.setLength(0);
file.writeInt(101); file.seek(file.length());
file.setLength(0);
file.writeInt(101); file.seek(file.length());
do
{ i=Fin.read(); if(i==-1) break;
Fout.write(i);
}while(i != -1);
Fin.close(); Fout.close();
} catch(FileNotFoundException e)
{ System.out.println("Error: Does not found output file"+ e);}
}
}