Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
9. Input Output in java
1. Input and Output in Java
By
Nilesh Dalvi
Lecturer, Patkar-Varde College.Lecturer, Patkar-Varde College.
http://www.slideshare.net/nileshdalvi01
Java and DataJava and Data
StructuresStructures
2. Introduction
• I/O is used to process the i/p and produce the o/p
based on the i/p
• Java uses the concept of stream to make operations
fast
• java.io package contains all the classes required for
input and output operations
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
3. Stream
• Stream: sequence of data
• In java, it is composed of bytes.
• Three streams:
– System.out : standard output stream
– System.in : standard input stream
– System.err : standard error stream
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
4. Reading Character from Console
• To read a character from console a
BufferedReader, used read().
• int read() throws IOException
• Each time that read() is called, it reads a
character from the input stream and returns it
as an integer value.
• Returns -1 when the end of the stream is
encounterd
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
8. Reading String from Console
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
9. File Class
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• Represents file and directory pathnames
• Use for creating files and directories,
searching files, file deletion.
• A file object is used to manipulates the
information associated with a disk file, such as
the permissions, time, date and directory path
and to navigate subdirectory.
11. Methods
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• public String getName()
– Returns the name of the file or directory denoted by this abstract pathname.
• public String getParent()
– Returns the pathname string of this abstract pathname's parent, or null if this
pathname does not name a parent directory.
• public File getParentFile()
– Returns the abstract pathname of this abstract pathname's parent, or null if
this pathname does not name a parent directory.
• public String getPath()
– Converts this abstract pathname into a pathname string.
• public boolean isAbsolute()
– Tests whether this abstract pathname is absolute. Returns true if this abstract
pathname is absolute, false otherwise
12. Methods
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• public String getAbsolutePath()
– Returns the absolute pathname string of this abstract pathname.
• public boolean canRead()
– Tests whether the application can read the file denoted by this abstract
pathname.
• public boolean canWrite()
– Tests whether the application can modify to the file denoted by this abstract
pathname
• public boolean exists()
– Tests whether the file or directory denoted by this abstract pathname exists.
• public boolean isDirectory()
– Tests whether the file denoted by this abstract pathname is a directory
• public boolean isFile()
– Tests whether the file denoted by this abstract pathname is a normal file.
13. Methods
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• public long lastModified()
– Returns the time that the file denoted by this abstract pathname was last
modified.
• public boolean createNewFile() throws IOException
– Atomically creates a new, empty file named by this abstract pathname if and
only if a file with this name does not yet exist.
• public boolean delete()
– Deletes the file or directory denoted by this abstract pathname.
• public String[] list()
– Returns an array of strings naming the files and directories in the directory
denoted by this abstract pathname.
• public String[] list(FilenameFilter filter)
– Returns an array of strings naming the files and directories in the directory
denoted by this abstract pathname that satisfy the specified filter.
14. Methods
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• public File[] listFiles()
– Returns an array of abstract pathnames denoting the files in the directory
denoted by this abstract pathname.
• public File[] listFiles(FileFilter filter)
– Returns an array of abstract pathnames denoting the files and directories in the
directory denoted by this abstract pathname that satisfy the specified filter.
• public boolean mkdir()
– Creates the directory named by this abstract pathname.
• public boolean mkdirs()
– Creates the directory named by this abstract pathname, including any necessary
but nonexistent parent directories.
• public boolean renameTo(File dest)
– Renames the file denoted by this abstract pathname.
16. Using FilenameFilter
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
String [] list (FilenameFilter fobj)
•Defines only single method, accept(), called
once for each file in a list.
boolean accept (File directory, String filename)
– True : for files included in list()
– False :for files excluded in list()
18. Stream Classes in Java
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• Stream can be defined as a sequence of data.
– InputStream : read data from source
– OutputStream : write data to a destination
• This are basic stream classes in Java
19. Need of Stream Classes
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• To perform read and write operation on
binary files we need a mechanism to read that
binary data on file/to write binary data.
• These classes are capable to read and write
one byte on binary files.
21. Byte Stream
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• Handles byte-oriented I/O
• A byte stream can be used with any type of
objects, including binary data.
22. InputStream Class
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• Abstract Class that defines Javas model of
streaming byte input
• Super class of all classes representing an input
stream of bytes
• All methods in this class will throw
IOException on error conditions.
• It is used to read data from a source, it may be
a file, an array peripheral device.
23. Commonly Used Methods
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Method Description
1) public abstract int read()throws
IOException:
reads the next byte of data from
the input stream.It returns -1 at the
end of file.
2) public int available()throws IOException:
returns an estimate of the number
of bytes that can be read from the
current input stream.
3) public void close()throws IOException:
is used to close the current input
stream.
24. OutputStream Class
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• Abstract Class that defines Javas model of
streaming byte Output
• Super class of all classes representing an
output stream of bytes
• All methods in this class will throw
IOException on error conditions.
25. Commonly Used Methods
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Method Description
1) public void write(int)throws IOException:
is used to write a byte to the
current output stream.
2) public void write(byte[])throws IOException:
is used to write an array of byte to
the current output stream.
3) public void flush()throws IOException flushes the current output stream.
4) public void close()throws IOException
is used to close the current output
stream.
26. FileInputStream and FileOutputStream Class
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• FileInputStream and FileOutputStream classes
are used to read and write data in file.
• In another words, they are used for file
handling in java.
27. FileOutputStream Class
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• Java FileOutputStream is an output stream for
writing data to a file.
• Write primitive values then use FileOutputStream.
• For character-oriented data, prefer FileWriter.
• But we can write byte-oriented as well as
character-oriented data.
28. FileOutputStream Class
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
import java.io.*;
class Test{
public static void main(String args[]){
try{
FileOutputstream fout = new FileOutputStream("abc.txt");
String s="Sachin Tendulkar is my favourite player";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}
catch(Exception e){
System.out.println(e);
}
}
}
29. FileInputStream Class
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• Java FileInputStream class obtains input bytes
from a file.
• It is used for reading streams of raw bytes such
as image data.
• For reading streams of characters, consider
using FileReader.
• It should be used to read byte-oriented data for
example to read image, audio, video etc.
30. FileInputStream Class
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
import java.io.*;
class SimpleRead{
public static void main(String args[]){
try{
FileInputStream fin = new FileInputStream("abc.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.println((char)i);
}
fin.close();
}catch(Exception e){
System.out.println(e);
}
}
}
31. ByteArrayOutputStream Class
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• Java ByteArrayOutputStream class is used to
write data into multiple files.
• In this stream, the data is written into a byte
array that can be written to multiple stream.
• ByteArrayOutputStream holds a copy of data
and forwards it to multiple streams.
• Buffer of ByteArrayOutputStream automatically
grows according to data.
32. Constructors
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• ByteArrayOutputStream()-creates a new byte
array output stream with the initial capacity of
32 bytes, though its size increases if necessary.
• ByteArrayOutputStream(int size)-creates a new
byte array output stream, with a buffer
capacity of the specified size, in bytes.
33. Methods
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Method Description
public synchronized void
writeTo(OutputStream out) throws
IOException
writes the complete contents of this
byte array output stream to the
specified output stream.
public void write(byte b) throws IOException writes byte into this stream.
public void write(byte[] b) throws
IOException
writes byte array into this stream.
public void flush() flushes this stream.
36. ByteArrayInputStream Class
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• The ByteArrayInputStream class allows us to read data
from byte arrays as streams.
• ByteArrayInputStream can thus wrap the byte array,
and turn it into a stream.
byte[] bytes = "Hello".getBytes(); //get byte array from somewhere.
InputStream input = new ByteArrayInputStream(bytes);
int data = input.read();
while(data != -1) {
//do something with data
data = input.read();
}
input.close();
37. FilterInputStream and FilterOutputStream Class
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• FilterInputStream and FilterOutputStream
are base classes for implementing our own
filtering output streams.
• Overrides all method of InputStream and
OutputStream Resp.
38. BufferedInputStream Class
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• The BufferedInputStream class provides buffering to
our input streams.
• Buffering can speed up IO quite a bit.
• Rather than read one byte at a time from the network
or disk, the BufferedInputStream reads a larger block
at a time.
• This is typically much faster, especially for disk access
and larger data amounts.
39. Constructors
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• BufferedInputStream(InputStream in)
• BufferedInputStream(InputStream in, int size)
Methods:
• Overrides all methods from FilterInputStream
class
40. BufferedInputStream Class
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
import java.io.*;
class BufferedInputStreamDemo{
public static void main(String args[]){
try
{
FileInputStream fin=new FileInputStream("f1.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
}
catch(Exception e){System.out.println(e);}
}
}
41. BufferedOutputStream Class
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• The BufferedOutputStream class provides buffering to
our output streams.
• Buffering can speed up IO quite a bit.
• Rather than write one byte at a time to the network or
disk, you write a larger block at a time.
• This is typically much faster, especially for disk access
and larger data amounts.
42. Constructors
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• BufferedOutputStream(OutputStream out, int size)
• BufferedOutputStream(OutputStream out)
Methods:
• Overrides all methods from FilterOutputStream
class
43. BufferedOutputStream Class
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
import java.io.*;
class BufferedOutputStreamDemo
{
public static void main(String args[])
{
try
{
FileOutputStream fout=new FileOutputStream("f1.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Hello World!";
byte b[]=s.getBytes();
bout.write(b);
bout.flush(); //flushes data from bout to fout
bout.close();
fout.close();
}
catch(Exception e){System.out.println(e);}
}
}
44. DataOutputStream Class
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• DataOutputStream class enables you to write Java
primitives to OutputStream's instead of only bytes.
• We wrap an OutputStream in a DataOutputStream
and then we can write primitives to it.
• Example:
19.99 12 Java T-shirt
9.99 8 Java Mug
45. DataInputStream Class
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• DataInputStream class enables us to read Java
primitives from InputStream's instead of only bytes.
• We wrap an InputStream in a DataInputStream and
then we can read primitives from it.
46. SequenceInputStream Class
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• SequenceInputStream combines two or more other
InputStream's into one.
• First all bytes from the first input stream is iterated
and returned, then the bytes from the second input
stream.
47. PushbackInputStream Class
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• PushbackInputStream is intendended to be used when
we parse data from an InputStream.
• Sometimes we need to read ahead a few bytes to see
what is coming, before we can determine how to
interprete the current byte.
• PushbackInputStream allows you to do that.
48. Character Streams
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• ByteStream classes handle the data in binary form
which is efficient for data processing.
• They cannot work directly with Unicode characters
• CharacterStream deals with the character oriented
text
• Characters are stored and retrieved in a human
readable form
49. Character Streams
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• Character Streams have two abstract classes
• They are
– Reader
– Writer
50. Reader Class
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• Reader Class is an abstract class that defines Java’s model of
streaming character input
• All of the methods in this class will throw an IOException on
error conditions
51. Writer Class
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• Writer Class is an abstract class that defines streaming
character output
• All of the methods in this class returns a void value and throw
an IOException in the case of errors
52. FileReader Class
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• FileReader class creates a Reader that you can use to read the
contents of a file
• Two most commonly used constructors:
– FileReader(String filePath)
– FileReader(File fileObj)
53. FileWriter class
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• FileWriter creates a Writer that you can use to write to a file
• Its most commonly used constructors are
– FileWriter(String filePath)
– FileWriter(String filePath, boolean append)
– FileWriter(File fileObj)
– FileWriter(File fileObj, boolean append)
54. CharArrayReader class
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• CharArrayReader class is an implementation of an input stream
that uses a character array as the source
• Is used to read an array of characters from a memory buffers
• Constructors
• CharArrayReader(char array[ ])
• CharArrayReader(char array[ ], int start, int numChars)
55. CharArrayWriter class
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• CharArrayWriter is an implementation of an output stream that
uses an array as the destination
• It is used for writing an array of characters to a memory buffer
• CharArrayWriter has two constructors
• CharArrayWriter( )
• CharArrayWriter(int numChars)