SlideShare a Scribd company logo
Instructor: @Subash @Paudyal
Training on Java
Programming
• What are streams?
• Java IO Streams
• Byte Oriented Streams
• Character Oriented Streams
• Byte Stream Classes
• FileInputStream, FileOutputStream
• BufferedInputStream, BufferedOutputStream
• DataInputStream, DataOutputStream
• PrintStream
• Character Stream Classes
• FileReader, FileWriter
• BufferedReader, BufferedWriter
• RandomAccessFile
• Files
• Directories
Session 12: Java Input Output
© paudyalsubash@yahoo.com 2
© paudyalsubash@yahoo.com 3
• Quickly and easily write programs that accomplish many common IO tasks :
• Reading and writing files
• Communicating over network connections
• Filtering data
• Interpreting a wide variety of formats for integer and floating-point numbers
• Encrypting and decrypting data
• Calculating digital signatures for streams
• Compressing and decompressing data
• Writing objects to streams
• Copying, moving, renaming, and getting information about files and directories
• Letting users choose files from a GUI interface
• Reading and writing non-English text in a variety of character sets
• Formatting integer and floating-point numbers as strings
• Talking directly to modems and other serial port devices
Objective
© paudyalsubash@yahoo.com 4
• A stream is an ordered sequence of bytes of undetermined length.
• Input streams move bytes of data into a Java program from some
generally external source. Like, like a siphon that sucks up water
• Output streams move bytes of data from Java to some generally external
target. Like, A hose that sprays out water
• A stream can represent many different kinds of sources and destinations,
including disk files, devices, network sockets other programs, and
memory arrays
• Streams support many different kinds of data, including simple bytes,
primitive data types, to advanced objects
• Provides interface to external world
Streams
© paudyalsubash@yahoo.com 5
• Input streams read bytes and output streams write bytes.
• Readers read characters and writers write characters.
• Therefore, to understand input and output, you first need a solid
understanding of how Java deals with bytes, integers, characters,
and other primitive data
• Integers: byte (8 bit) , Short (16 bits), Int (32 bits), Long (64 bits)
• Java support only int literal, no byte and short are available
• byte b=42 and short s=24000; //compiler does conversion here
• Byte b1=5, b2=7; Byte b3=b1+b2; is also error as when bytes are
added it gives integer output and that can’t be assigned to byte
What to read and write?
© paudyalsubash@yahoo.com 6
• Standard output (to Screen/Console)
• System.out
• System.out.println(“Hello”);
• System.err
• System.err.println(“Stop”);
• Standard input (from keyboard)
• System.in
• System.in.read();
• Java io files are available in package java.io.*;
• Java’s stream-based I/O is based on four abstract classes:
• Byte Streams (InputStream, OutputStream) – used when working with bytes or other
binary objects
• Character Streams (Reader, and Writer) – used when working with characters or
strings
Data IO in java
© paudyalsubash@yahoo.com 7
• Programs use byte streams to perform input and output of 8-bit
bytes.
• The byte stream classes provide a rich environment for handling byte-
oriented I/O.
• A byte stream can be used with any type of object, including binary
data. This versatility makes byte streams important to many types of
programs.
• All byte stream classes are descended from InputStream and
OutputStream
• Every things is read as byte form (signed integer that ranges from -
128 to 127)
• Java stream classes accept and return int which are internally
converted to byte
Input and Output Byte Streams
© paudyalsubash@yahoo.com 8
• InputStream is an abstract class that defines Java’s model of streaming byte
input
• Most of the methods in this class will throw an IOException when an I/O
error occurs
• We use the derived classes to perform input functions. Some functions are:
• read() read a byte from input stream
• read(byte[] b) read a byte array from input into b
• read(byte[]b, int n, int m) read m bytes into b from nth byte
• available() gives number of bytes in input
• skip(n) skips n bytes from input stream
• reset() goes back to beginning of stream
• close() closes the input stream
• Read() method returns actual number of bytes that were successfully read
or-1 if end of the file is reached.
InputStream
© paudyalsubash@yahoo.com 9
• OutputStream is an abstract class that defines streaming byte
output.
• Most of the methods in this class return void and throw an
IOException in the case of I/O errors.
• OutputStream has following methods:
• write() write a byte to output stream
• write(byte[] b) write all bytes in b into output stream
• write(byte[] b, int n, int m) write m bytes from array b from n’th
• close() Closes the output stream
• flush() flushes the output stream
OutputStream
© paudyalsubash@yahoo.com 10
• The hierarchy of input streams follows similar lines as output streams.
• System.in is an instance of InputStream.
• System.out and System.err are instances of PrintStream.
Input Streams and Output Streams
OutputStream
ByteArray
OutputStream
FileOutput
Stream
FilterOutput
Stream
PipedOutput
Stream
Buffered
OutputStream
PrintStream
DataOutput
Stream
© paudyalsubash@yahoo.com 11
• FileInputStream class creates an InputStream that you can use
to read bytes from a file.
• Constructors:
• FileInputStream(String filePath)
• FileInputStream(File fileObj)
• Code
• FileInputStream f0 = new FileInputStream("/autoexec.bat")
• File f = new File("/autoexec.bat");
• FileInputStream f1 = new FileInputStream(f);
FileInputStream
© paudyalsubash@yahoo.com 12
• FileOutputStream creates an OutputStream that you can use to
write bytes to a file.
• Constructors:
• FileOutputStream(String filePath)
• FileOutputStream(File fileObj)
• FileOutputStream(String filePath, boolean append)
• FileOutputStream(File fileObj, boolean append)
FileOutputStream
© paudyalsubash@yahoo.com 13
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(“file1.txt");
out = new FileOutputStream(“file2.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c); }
}
finally {
if (in != null) {
in.close(); }
if (out != null) {
out.close(); }
}
© paudyalsubash@yahoo.com 14
• Filtered streams are simply wrappers around underlying input or output
streams that transparently provide some extended level of functionality.
• These streams are typically accessed by methods that are expecting a
generic stream
• The filtered byte streams are
• FilterInputStream and
• FilterOutputStream
• The methods provided in these classes are identical to those in
InputStream and OutputStream.
• We deal with the classes derived from Filtered Streams
• Buffered Streams
• Print Streams
• Data Streams
Filtered Streams
© paudyalsubash@yahoo.com 15
• The java.io.DataInputStream and java.io.DataOutputStream classes are
subclasses of FilterInputStream and FilterOutputStream , respectively.
• For the byte-oriented streams, a buffered stream extends a filtered stream
class by attaching a memory buffer to the I/O stream.
• This buffer allows Java to do I/O operations on more than a byte at a time,
thereby improving performance.
• The buffered byte stream classes are BufferedInputStream and
BufferedOutputStream.
• class allows you to "wrap" any InputStream into a buffered stream to
improve performance
• Constructors:
• BufferedInputStream(InputStream inputStream)
• BufferedInputStream(InputStream inputStream, int bufSize)
Buffered Streams
© paudyalsubash@yahoo.com 16
• The PrintStream class provides all of the output capabilities we have
been using from the System file handle, System.out,
• Constructors
• PrintStream(OutputStream outputStream)
• PrintStream(OutputStream outputStream, boolean flushOnNewline)
• PrintStream(OutputStream outputStream, boolean flushOnNewline, String charSet)
• PrintStream supports the print( ) and println( ) methods for all types,
including Object. If an argument is not a primitive type, the
PrintStream methods will call the object’s toString( ) method and
then display the result.
• After JDK5, printf() method was added that allows to specify the
precise format of the data to be written
• PrintStream printf(String fmtString, Object … args)
PrintStream
© paudyalsubash@yahoo.com 17
• Data streams support binary I/O of primitive data type values
(boolean, char, byte, short, int, long, float, and double) as well as
String values.
• DataOutput defines methods that convert values of a primitive
type into a byte sequence and then writes it to the underlying
stream.
• Constructor
• DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
• DataOutputStream dos = new DataOutputStream(new FileOutputStream("output.dat"));
• DataInputStream is the complement of DataOuputStream and
the methods are also equivalent such as readDouble()
DataOutput and DataInput
© paudyalsubash@yahoo.com 18
© paudyalsubash@yahoo.com 19
• the only reliable way to write a String so that it can be recovered
by a DataInputStream is to use UTF-8 encoding, accomplished in
this example using writeUTF( ) and readUTF( )
• UTF-8 is a multi-byte format, and the length of encoding varies
according to the actual character set in use.
• Unicode is a tremendous waste of space and/or bandwidth, so
UTF-8 encodes ASCII characters in a single byte, and non-ASCII
characters in two or three bytes.
• out.writeUTF("Square root of 2");
• System.out.println(in.readUTF());
UTF Format
© paudyalsubash@yahoo.com 20
//First, write the data
DataOutputStream dout =
new DataOutputStream(new
FileOutputStream("Test.dat"));
try {
dout.writeDouble(98.6);
dout.writeInt(1000);
dout.writeBoolean(true);
} catch(FileNotFoundException e) {
System.out.println("Cannot Open Output
File");
return;
} catch(IOException e) {
System.out.println("I/O Error: " + e);
}
// Now, read the data back.
DataInputStream din =
new DataInputStream(new
FileInputStream("Test.dat"));
try{
double d = din.readDouble();
int i = din.readInt();
boolean b = din.readBoolean();
System.out.println("Here are the values: " +
d + " " + i + " " + b);
} catch(FileNotFoundException e) {
System.out.println("Cannot Open Input File");
return;
} catch(IOException e) {
System.out.println("I/O Error: " + e);
}
© paudyalsubash@yahoo.com 21
Exceptions in IO
© paudyalsubash@yahoo.com 22
• Bytes copy seems like a normal program, but it actually
represents a kind of low-level I/O that you should avoid.
• Since abc.txt contains character data, the best approach is to use
character streams, as discussed in the next section.
• There are also streams for more complicated data types. Byte
streams should only be used for the most primitive I/O.
• So why we learn about byte streams?
• Because all other stream types are built on byte streams
When Not to Use Byte Streams
© paudyalsubash@yahoo.com 23
• Readers and writers are based on characters, which can have varying widths
depending on the character set.
• ASCII and ISO Latin-1 use one-byte characters. Unicode uses two-byte characters
• Since characters are ultimately composed of bytes, readers take their input from
streams.
• However, they convert those bytes into chars according to a specified encoding
format before passing them along.
• Similarly, writers convert chars to bytes according to a specified encoding before
writing them onto some underlying stream.
• I/O with character streams is no more complicated than I/O with byte streams.
• All character stream classes are descended from Reader and Writer.
• The most important reason for the Reader and Writer hierarchies is for
internationalization.
Character Streams
© paudyalsubash@yahoo.com 24
• The FileReader class creates a Reader that you can use to read
the contents of a file.
• Reading from file
• FileReader(String filePath)
• FileReader(File fileObj)
• Writing to File
• FileWriter(String fileName)
• FileWriter(String fileName, boolean append)
• If append is true, then the file is appended not overwritten
FileReader and FileWriter
© paudyalsubash@yahoo.com 25
FileReader inputStream = null;
FileWriter outputStream = null;
try {
inputStream = new FileReader(“file1.txt");
outputStream = new FileWriter(“file2.txt");
int c;
while ((c = inputStream.read()) != -1) {
outputStream.write(c); }
}
finally {
if (inputStream != null) {
inputStream.close(); }
if (outputStream != null) {
outputStream.close(); }
} Note: In, Character Copy the int variable holds a character value in its last 16 bits; In Bytes Copy, the int variable holds a byte value in its last 8 bits.
© paudyalsubash@yahoo.com 26
BufferedReader inputStream = null;
PrintWriter outputStream = null;
try {
inputStream = new BufferedReader(new FileReader("xanadu.txt"));
outputStream = new PrintWriter(new FileWriter("characteroutput.txt"));
String l;
while ((l = inputStream.readLine()) != null) {
outputStream.println(l); }
}
finally {
if (inputStream != null) {
inputStream.close(); }
if (outputStream != null) {
outputStream.close(); }
}
Buffered Reader and Writer
We can wrap the FileWriter object to the Buffered Writer to achieve higher performance
Eg. PrintWriter outputStream = new PrintWriter(new BufferedWriter(new FileWriter(file)));
© paudyalsubash@yahoo.com 27
• File input and output streams require you to start reading or writing at the beginning of a file and
then read or write the file in order
• Sometimes, however, you need to read parts of a file in a more or less random order, where the data
near the beginning of the file isn't necessarily read before the data nearer the end.
• Other times you need to both read and write the same file
• Random-access files can be read from or written to or both from a particular byte position in the file.
• The RandomAccessFile class implements both the DataInput and DataOutput interfaces. Therefore,
reads and writes use methods exactly like methods of the DataInputStream and DataOutputStream.
• Constructor
• RandomAccessFile(File fileObj, String access)
• RandomAccessFile(String filename, String access)
• Access defines the file permission ie. r or rw (also rws/rwd)
• Methods
• void seek(long newPos)
• long getFilePointer()
• long length() //find length of file
RandomAccessFile
© paudyalsubash@yahoo.com 28
//Reading from file
RandomAccessFile file = new RandomAccessFile("d:abc.txt", "r");
file.seek(150);
byte[] bytes = new byte[23];
file.read(bytes);
file.close();
System.out.println(new String(bytes));
//Writing to file
String data=“Java Rocks!!!”;
RandomAccessFile file = new RandomAccessFile(“d:abc.txt”, "rw");
file.seek(22);
file.write(data.getBytes());
file.close()
Example
© paudyalsubash@yahoo.com 29
• Most of the classes defined by java.io operate on streams, the
File class does not.
• File deals directly with files and the file system. That is, the File
class does not specify how information is retrieved from or
stored in files; it describes the properties of a file itself.
• File object is used to obtain or manipulate the information
associated with a disk file, such as the permissions, time, date,
and directory path, and to navigate subdirectory hierarchies.
• We should use standard stream input/output classes to direct
access for reading and writing file data
File (java.io.File)
© paudyalsubash@yahoo.com 30
• Constructor
• File(String directoryPath)
• File(String directoryPath, String filename)
• To Get Paths
• getAbsolutePath(), getPath(), getParent(), getCanonicalPath()
• To Check Files
• isFile(), isDirectory(), exists()
• To Get File Properties
• getName(), length(), isAbsolute(), lastModified(), isHidden() //length in bytes
• To Get File Permissions
• canRead(), can Write(), canExecute()
• To Know Storage information
• getFreeSpace(), getUsableSpace(), getTotalSpace()
• Utility Functions
• Boolean createNewFile()
• Boolean renameTo(File nf); renames the file and returns true if success
• Boolean delete(); deletes the file represented by path of file (also delete directory if its empty)
• Boolean setLastModified(long ms) sets timestamp(Jan 1, 1970 UTC as a start time)
• Boolean setReadOnly() to mark file as readable (also can be done writable, and executable.)
© paudyalsubash@yahoo.com 31
• You can create an instance of File from a String pathname:
• File fooFile = new File( "/tmp/foo.txt" );
• File fooFile = new File( "/tmp", "foo.txt" );
• File barDir = new File( "/tmp/bar" );
• You can also create a file with a relative path:
• File f = new File( "foo" );
• In this case, Java works relative to the current directory of the Java interpreter. Can find
the current directory by checking the user.dir property in the System Properties list:
System.getProperty("user.dir"));
• The static method createTempFile(string prefix, string suffix ) , creates a file in a specified
location using an automatically generated unique name
• Use int compareTo(File f) to compare two files.
• Use the static method File.listRoots( ) to know about all the top-level directories, such as
C:, D: etc
• File[] drives = File.listRoots( );
© paudyalsubash@yahoo.com 32
• A directory is a File that contains a list of other files and
directories.
• When you create a File object that is directory, the isDirectory( )
method will return true and you can use list() method
• Methods
• String[] list( ) extract the list of files and directories inside
• File[] listFiles() return array of File objects
• File[] listFiles(FileFilter ff) return File that satisfied FileFilter which uses
Boolean accept(File path) that match path argument
• Boolean mkdir()/mkdirs() create specify directory / with path
Directory
© paudyalsubash@yahoo.com 33
String dirname = "/java";
File f1 = new File(dirname);
if (f1.isDirectory()) {
System.out.println(“Reading Directory = " + dirname);
String s[] = f1.list();
for (int i=0; i < s.length; i++) {
File f = new File(dirname + "/" + s[i]);
if (f.isDirectory())
System.out.println(s[i] + " is a directory");
else
System.out.println(s[i] + " is a file");
}
Code
• Queries?
End of Java IO
© paudyalsubash@yahoo.com 34
© paudyalsubash@yahoo.com 35
• How is a -1 that appears as a part of data to be distinguished from a -1 indicating end of stream?
• Read() function doesn’t return a byte; its signature says it return an integers. This int is not a java byte with value between -128 to
+127 but a more general byte with value between 0 and 255. Hence -1 can be easily distinguished.
• How conversion?
• Since bytes have such a small range, they're often converted to ints in calculations and method invocations.
• Casting from an int to a byte—for that matter, casting from any wider integer type to a narrower type—takes place through
truncation of the high-order bytes.
• This means that as long as the value of the wider type can be expressed in the narrower type, the value is not changed. The int 127
cast to a byte still retains the value 127. On the other hand, if the int value is too large for a byte, strange things happen. So, 128 will
be 10000000 is -127 How? (absolute value of –ve number is found by taking complement and adding 1 to it)
• How characters are treated?
• Since computers only really understand numbers, characters are encoded by matching each character in a given script to a particular
number. For example, in the common ASCII encoding, the character A is mapped to the number 65;
• ASCII, the American Standard Code for Information Interchange, is a seven-bit character set. Thus it defines 27 or 128 different
characters whose numeric values range from to 127. These characters are sufficient for handling most of American English
• How Character Stream work?
• Character-oriented data in Java is primarily composed of the char primitive data type . you need to understand chars to understand
how reader and writer works.
• In Java, a char is a two-byte, unsigned integer, the only unsigned type in Java. Thus, possible char values range from 0 to 65,535.
Chars may be assigned to by using int literals in this range
• chars may also be assigned to by using char literals; that is, the character itself enclosed in single quotes.
© paudyalsubash@yahoo.com 36
• difference between an 8-bit byte and a 32-bit int ?
• is insignificant for a single number
• it can be very significant when several thousand to several million
numbers are read.
• In fact, a single byte still takes up four bytes of space inside the Java
virtual machine, but
• byte array only occupies the amount of space it actually needs.
• The virtual machine includes special instructions for operating on
byte arrays, but
• does not include any instructions for operating on single bytes.
They're just promoted to int.
How JVM treats byte & byte[]
© paudyalsubash@yahoo.com 37
• You often want to look for a particular kind of file—for example, text files, image files etc.
• Need a FilenameFilter or FileFilter object that specifies which files you'll accept
• FilenameFilter is an interface with method
• Public abstract Boolean accept(File dir,String name)
• FileFilter is an interface with method
• Public abstract Boolean accept(File dir)
• public File[] listFiles(FilenameFilter filter)
• public File[] listFiles(FileFilter filter)
public class ImageFilter implements FilenameFilter {
public boolean accept(File directory, String name) {
if (name.endsWith(".jpg")) return true;
if (name.endsWith(".jpeg")) return true;
return false;
}
//public class HTMLFilter implements FileFilter {
//public boolean accept(File pathname) {
//if (pathname.getName().endsWith(".html")) return true; }
File dir = new File("/public/picture/");
File[] imgs = dir.listFiles(new ImageFilter());
Read Filtered Files only
© paudyalsubash@yahoo.com 38
• Open the file
Character Chart

More Related Content

What's hot (20)

Java Threads
Java ThreadsJava Threads
Java Threads
M Vishnuvardhan Reddy
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37
myrajendra
 
Packages and interfaces
Packages and interfacesPackages and interfaces
Packages and interfaces
vanithaRamasamy
 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and files
Marcello Thiry
 
Polymorphism in java
Polymorphism in java Polymorphism in java
Polymorphism in java
Janu Jahnavi
 
Java Strings
Java StringsJava Strings
Java Strings
RaBiya Chaudhry
 
File Handling in Java Oop presentation
File Handling in Java Oop presentationFile Handling in Java Oop presentation
File Handling in Java Oop presentation
Azeemaj101
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
VINOTH R
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
Praveen M Jigajinni
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
Binoj T E
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
Benj Del Mundo
 
Java-java virtual machine
Java-java virtual machineJava-java virtual machine
Java-java virtual machine
Surbhi Panhalkar
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
teach4uin
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
Emertxe Information Technologies Pvt Ltd
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
AmbigaMurugesan
 
Constants, Variables and Data Types in Java
Constants, Variables and Data Types in JavaConstants, Variables and Data Types in Java
Constants, Variables and Data Types in Java
Abhilash Nair
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
lalithambiga kamaraj
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
Pooja Jaiswal
 
Threads concept in java
Threads concept in javaThreads concept in java
Threads concept in java
Muthukumaran Subramanian
 

Viewers also liked (20)

Java I/O
Java I/OJava I/O
Java I/O
Jussi Pohjolainen
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
Sunil OS
 
Various io stream classes .47
Various io stream classes .47Various io stream classes .47
Various io stream classes .47
myrajendra
 
Files in java
Files in javaFiles in java
Files in java
Muthukumaran Subramanian
 
Java IO Package and Streams
Java IO Package and StreamsJava IO Package and Streams
Java IO Package and Streams
babak danyal
 
Handling I/O in Java
Handling I/O in JavaHandling I/O in Java
Handling I/O in Java
Hiranya Jayathilaka
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
Nilesh Dalvi
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
kamal kotecha
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
Intelligo Technologies
 
C++ to java
C++ to javaC++ to java
C++ to java
Gebze Technical University
 
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsJedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Don Bosco BSIT
 
Unit v
Unit vUnit v
Unit v
snehaarao19
 
Character stream classes .52
Character stream classes .52Character stream classes .52
Character stream classes .52
myrajendra
 
Byte stream classes.49
Byte stream classes.49Byte stream classes.49
Byte stream classes.49
myrajendra
 
Nested classes in java
Nested classes in javaNested classes in java
Nested classes in java
Richa Singh
 
Inner classes9 cm604.28
Inner classes9 cm604.28Inner classes9 cm604.28
Inner classes9 cm604.28
myrajendra
 
Inner classes
Inner classesInner classes
Inner classes
DraftKing Zohaib
 
I/O in java Part 1
I/O in java Part 1I/O in java Part 1
I/O in java Part 1
ashishspace
 
Inner classes ,annoumous and outer classes in java
Inner classes ,annoumous and outer classes in javaInner classes ,annoumous and outer classes in java
Inner classes ,annoumous and outer classes in java
Adil Mehmoood
 
Java API, Exceptions and IO
Java API, Exceptions and IOJava API, Exceptions and IO
Java API, Exceptions and IO
Jussi Pohjolainen
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
Sunil OS
 
Various io stream classes .47
Various io stream classes .47Various io stream classes .47
Various io stream classes .47
myrajendra
 
Java IO Package and Streams
Java IO Package and StreamsJava IO Package and Streams
Java IO Package and Streams
babak danyal
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
Nilesh Dalvi
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
kamal kotecha
 
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsJedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Don Bosco BSIT
 
Character stream classes .52
Character stream classes .52Character stream classes .52
Character stream classes .52
myrajendra
 
Byte stream classes.49
Byte stream classes.49Byte stream classes.49
Byte stream classes.49
myrajendra
 
Nested classes in java
Nested classes in javaNested classes in java
Nested classes in java
Richa Singh
 
Inner classes9 cm604.28
Inner classes9 cm604.28Inner classes9 cm604.28
Inner classes9 cm604.28
myrajendra
 
I/O in java Part 1
I/O in java Part 1I/O in java Part 1
I/O in java Part 1
ashishspace
 
Inner classes ,annoumous and outer classes in java
Inner classes ,annoumous and outer classes in javaInner classes ,annoumous and outer classes in java
Inner classes ,annoumous and outer classes in java
Adil Mehmoood
 
Ad

Similar to Java Input Output (java.io.*) (20)

Java development development Files lectur6.ppt
Java development development Files lectur6.pptJava development development Files lectur6.ppt
Java development development Files lectur6.ppt
rafeakrafeak
 
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
Monhocvecaujahetvagiuplaptunhhayhonha.pdfMonhocvecaujahetvagiuplaptunhhayhonha.pdf
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
cuchuoi83ne
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
HindAlmisbahi
 
IOstreams hgjhsgfdjyggckhgckhjxfhbuvobunciu
IOstreams hgjhsgfdjyggckhgckhjxfhbuvobunciuIOstreams hgjhsgfdjyggckhgckhjxfhbuvobunciu
IOstreams hgjhsgfdjyggckhgckhjxfhbuvobunciu
akinbhattarai1
 
CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxCHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptx
SadhilAggarwal
 
Io stream
Io streamIo stream
Io stream
Parthipan Parthi
 
Advanced programming ch2
Advanced programming ch2Advanced programming ch2
Advanced programming ch2
Gera Paulos
 
Java I/O
Java I/OJava I/O
Java I/O
Jayant Dalvi
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
VithalReddy3
 
Javaiostream
JavaiostreamJavaiostream
Javaiostream
Manav Prasad
 
IO Programming.pptx all informatiyon ppt
IO Programming.pptx all informatiyon pptIO Programming.pptx all informatiyon ppt
IO Programming.pptx all informatiyon ppt
nandinimakwana22cse
 
Java Tutorial Lab 6
Java Tutorial Lab 6Java Tutorial Lab 6
Java Tutorial Lab 6
Berk Soysal
 
Javaiostream
JavaiostreamJavaiostream
Javaiostream
Tien Nguyen
 
javaiostream
javaiostreamjavaiostream
javaiostream
Arjun Shanka
 
Programming language JAVA Input output opearations
Programming language JAVA Input output opearationsProgramming language JAVA Input output opearations
Programming language JAVA Input output opearations
2025183005
 
Apache Arrow Workshop at VLDB 2019 / BOSS Session
Apache Arrow Workshop at VLDB 2019 / BOSS SessionApache Arrow Workshop at VLDB 2019 / BOSS Session
Apache Arrow Workshop at VLDB 2019 / BOSS Session
Wes McKinney
 
Using Input Output
Using Input OutputUsing Input Output
Using Input Output
raksharao
 
Java input output package
Java input output packageJava input output package
Java input output package
Sujit Kumar
 
Files io
Files ioFiles io
Files io
Narayana Swamy
 
Basic IO
Basic IOBasic IO
Basic IO
Ravi_Kant_Sahu
 
Java development development Files lectur6.ppt
Java development development Files lectur6.pptJava development development Files lectur6.ppt
Java development development Files lectur6.ppt
rafeakrafeak
 
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
Monhocvecaujahetvagiuplaptunhhayhonha.pdfMonhocvecaujahetvagiuplaptunhhayhonha.pdf
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
cuchuoi83ne
 
IOstreams hgjhsgfdjyggckhgckhjxfhbuvobunciu
IOstreams hgjhsgfdjyggckhgckhjxfhbuvobunciuIOstreams hgjhsgfdjyggckhgckhjxfhbuvobunciu
IOstreams hgjhsgfdjyggckhgckhjxfhbuvobunciu
akinbhattarai1
 
CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxCHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptx
SadhilAggarwal
 
Advanced programming ch2
Advanced programming ch2Advanced programming ch2
Advanced programming ch2
Gera Paulos
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
VithalReddy3
 
IO Programming.pptx all informatiyon ppt
IO Programming.pptx all informatiyon pptIO Programming.pptx all informatiyon ppt
IO Programming.pptx all informatiyon ppt
nandinimakwana22cse
 
Java Tutorial Lab 6
Java Tutorial Lab 6Java Tutorial Lab 6
Java Tutorial Lab 6
Berk Soysal
 
Programming language JAVA Input output opearations
Programming language JAVA Input output opearationsProgramming language JAVA Input output opearations
Programming language JAVA Input output opearations
2025183005
 
Apache Arrow Workshop at VLDB 2019 / BOSS Session
Apache Arrow Workshop at VLDB 2019 / BOSS SessionApache Arrow Workshop at VLDB 2019 / BOSS Session
Apache Arrow Workshop at VLDB 2019 / BOSS Session
Wes McKinney
 
Using Input Output
Using Input OutputUsing Input Output
Using Input Output
raksharao
 
Java input output package
Java input output packageJava input output package
Java input output package
Sujit Kumar
 
Ad

Recently uploaded (20)

IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
Best Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small BusinessesBest Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small Businesses
TheTelephony
 
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
Insurance Tech Services
 
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentricIntegration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Natan Silnitsky
 
OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native BarcelonaOpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA TechnologiesAI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Natan Silnitsky
 
14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework
Angelo Theodorou
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptxwAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
How Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines OperationsHow Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines Operations
Insurance Tech Services
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
COBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM CertificateCOBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM Certificate
VICTOR MAESTRE RAMIREZ
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
Best Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small BusinessesBest Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small Businesses
TheTelephony
 
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
Insurance Tech Services
 
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentricIntegration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Natan Silnitsky
 
OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native BarcelonaOpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA TechnologiesAI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Natan Silnitsky
 
14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework
Angelo Theodorou
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptxwAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
How Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines OperationsHow Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines Operations
Insurance Tech Services
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
COBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM CertificateCOBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM Certificate
VICTOR MAESTRE RAMIREZ
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 

Java Input Output (java.io.*)

  • 2. • What are streams? • Java IO Streams • Byte Oriented Streams • Character Oriented Streams • Byte Stream Classes • FileInputStream, FileOutputStream • BufferedInputStream, BufferedOutputStream • DataInputStream, DataOutputStream • PrintStream • Character Stream Classes • FileReader, FileWriter • BufferedReader, BufferedWriter • RandomAccessFile • Files • Directories Session 12: Java Input Output © [email protected] 2
  • 3. © [email protected] 3 • Quickly and easily write programs that accomplish many common IO tasks : • Reading and writing files • Communicating over network connections • Filtering data • Interpreting a wide variety of formats for integer and floating-point numbers • Encrypting and decrypting data • Calculating digital signatures for streams • Compressing and decompressing data • Writing objects to streams • Copying, moving, renaming, and getting information about files and directories • Letting users choose files from a GUI interface • Reading and writing non-English text in a variety of character sets • Formatting integer and floating-point numbers as strings • Talking directly to modems and other serial port devices Objective
  • 4. © [email protected] 4 • A stream is an ordered sequence of bytes of undetermined length. • Input streams move bytes of data into a Java program from some generally external source. Like, like a siphon that sucks up water • Output streams move bytes of data from Java to some generally external target. Like, A hose that sprays out water • A stream can represent many different kinds of sources and destinations, including disk files, devices, network sockets other programs, and memory arrays • Streams support many different kinds of data, including simple bytes, primitive data types, to advanced objects • Provides interface to external world Streams
  • 5. © [email protected] 5 • Input streams read bytes and output streams write bytes. • Readers read characters and writers write characters. • Therefore, to understand input and output, you first need a solid understanding of how Java deals with bytes, integers, characters, and other primitive data • Integers: byte (8 bit) , Short (16 bits), Int (32 bits), Long (64 bits) • Java support only int literal, no byte and short are available • byte b=42 and short s=24000; //compiler does conversion here • Byte b1=5, b2=7; Byte b3=b1+b2; is also error as when bytes are added it gives integer output and that can’t be assigned to byte What to read and write?
  • 6. © [email protected] 6 • Standard output (to Screen/Console) • System.out • System.out.println(“Hello”); • System.err • System.err.println(“Stop”); • Standard input (from keyboard) • System.in • System.in.read(); • Java io files are available in package java.io.*; • Java’s stream-based I/O is based on four abstract classes: • Byte Streams (InputStream, OutputStream) – used when working with bytes or other binary objects • Character Streams (Reader, and Writer) – used when working with characters or strings Data IO in java
  • 7. © [email protected] 7 • Programs use byte streams to perform input and output of 8-bit bytes. • The byte stream classes provide a rich environment for handling byte- oriented I/O. • A byte stream can be used with any type of object, including binary data. This versatility makes byte streams important to many types of programs. • All byte stream classes are descended from InputStream and OutputStream • Every things is read as byte form (signed integer that ranges from - 128 to 127) • Java stream classes accept and return int which are internally converted to byte Input and Output Byte Streams
  • 8. © [email protected] 8 • InputStream is an abstract class that defines Java’s model of streaming byte input • Most of the methods in this class will throw an IOException when an I/O error occurs • We use the derived classes to perform input functions. Some functions are: • read() read a byte from input stream • read(byte[] b) read a byte array from input into b • read(byte[]b, int n, int m) read m bytes into b from nth byte • available() gives number of bytes in input • skip(n) skips n bytes from input stream • reset() goes back to beginning of stream • close() closes the input stream • Read() method returns actual number of bytes that were successfully read or-1 if end of the file is reached. InputStream
  • 9. © [email protected] 9 • OutputStream is an abstract class that defines streaming byte output. • Most of the methods in this class return void and throw an IOException in the case of I/O errors. • OutputStream has following methods: • write() write a byte to output stream • write(byte[] b) write all bytes in b into output stream • write(byte[] b, int n, int m) write m bytes from array b from n’th • close() Closes the output stream • flush() flushes the output stream OutputStream
  • 10. © [email protected] 10 • The hierarchy of input streams follows similar lines as output streams. • System.in is an instance of InputStream. • System.out and System.err are instances of PrintStream. Input Streams and Output Streams OutputStream ByteArray OutputStream FileOutput Stream FilterOutput Stream PipedOutput Stream Buffered OutputStream PrintStream DataOutput Stream
  • 11. © [email protected] 11 • FileInputStream class creates an InputStream that you can use to read bytes from a file. • Constructors: • FileInputStream(String filePath) • FileInputStream(File fileObj) • Code • FileInputStream f0 = new FileInputStream("/autoexec.bat") • File f = new File("/autoexec.bat"); • FileInputStream f1 = new FileInputStream(f); FileInputStream
  • 12. © [email protected] 12 • FileOutputStream creates an OutputStream that you can use to write bytes to a file. • Constructors: • FileOutputStream(String filePath) • FileOutputStream(File fileObj) • FileOutputStream(String filePath, boolean append) • FileOutputStream(File fileObj, boolean append) FileOutputStream
  • 13. © [email protected] 13 FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream(“file1.txt"); out = new FileOutputStream(“file2.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } }
  • 14. © [email protected] 14 • Filtered streams are simply wrappers around underlying input or output streams that transparently provide some extended level of functionality. • These streams are typically accessed by methods that are expecting a generic stream • The filtered byte streams are • FilterInputStream and • FilterOutputStream • The methods provided in these classes are identical to those in InputStream and OutputStream. • We deal with the classes derived from Filtered Streams • Buffered Streams • Print Streams • Data Streams Filtered Streams
  • 15. © [email protected] 15 • The java.io.DataInputStream and java.io.DataOutputStream classes are subclasses of FilterInputStream and FilterOutputStream , respectively. • For the byte-oriented streams, a buffered stream extends a filtered stream class by attaching a memory buffer to the I/O stream. • This buffer allows Java to do I/O operations on more than a byte at a time, thereby improving performance. • The buffered byte stream classes are BufferedInputStream and BufferedOutputStream. • class allows you to "wrap" any InputStream into a buffered stream to improve performance • Constructors: • BufferedInputStream(InputStream inputStream) • BufferedInputStream(InputStream inputStream, int bufSize) Buffered Streams
  • 16. © [email protected] 16 • The PrintStream class provides all of the output capabilities we have been using from the System file handle, System.out, • Constructors • PrintStream(OutputStream outputStream) • PrintStream(OutputStream outputStream, boolean flushOnNewline) • PrintStream(OutputStream outputStream, boolean flushOnNewline, String charSet) • PrintStream supports the print( ) and println( ) methods for all types, including Object. If an argument is not a primitive type, the PrintStream methods will call the object’s toString( ) method and then display the result. • After JDK5, printf() method was added that allows to specify the precise format of the data to be written • PrintStream printf(String fmtString, Object … args) PrintStream
  • 17. © [email protected] 17 • Data streams support binary I/O of primitive data type values (boolean, char, byte, short, int, long, float, and double) as well as String values. • DataOutput defines methods that convert values of a primitive type into a byte sequence and then writes it to the underlying stream. • Constructor • DataInputStream dis = new DataInputStream(new FileInputStream("data.txt")); • DataOutputStream dos = new DataOutputStream(new FileOutputStream("output.dat")); • DataInputStream is the complement of DataOuputStream and the methods are also equivalent such as readDouble() DataOutput and DataInput
  • 19. © [email protected] 19 • the only reliable way to write a String so that it can be recovered by a DataInputStream is to use UTF-8 encoding, accomplished in this example using writeUTF( ) and readUTF( ) • UTF-8 is a multi-byte format, and the length of encoding varies according to the actual character set in use. • Unicode is a tremendous waste of space and/or bandwidth, so UTF-8 encodes ASCII characters in a single byte, and non-ASCII characters in two or three bytes. • out.writeUTF("Square root of 2"); • System.out.println(in.readUTF()); UTF Format
  • 20. © [email protected] 20 //First, write the data DataOutputStream dout = new DataOutputStream(new FileOutputStream("Test.dat")); try { dout.writeDouble(98.6); dout.writeInt(1000); dout.writeBoolean(true); } catch(FileNotFoundException e) { System.out.println("Cannot Open Output File"); return; } catch(IOException e) { System.out.println("I/O Error: " + e); } // Now, read the data back. DataInputStream din = new DataInputStream(new FileInputStream("Test.dat")); try{ double d = din.readDouble(); int i = din.readInt(); boolean b = din.readBoolean(); System.out.println("Here are the values: " + d + " " + i + " " + b); } catch(FileNotFoundException e) { System.out.println("Cannot Open Input File"); return; } catch(IOException e) { System.out.println("I/O Error: " + e); }
  • 22. © [email protected] 22 • Bytes copy seems like a normal program, but it actually represents a kind of low-level I/O that you should avoid. • Since abc.txt contains character data, the best approach is to use character streams, as discussed in the next section. • There are also streams for more complicated data types. Byte streams should only be used for the most primitive I/O. • So why we learn about byte streams? • Because all other stream types are built on byte streams When Not to Use Byte Streams
  • 23. © [email protected] 23 • Readers and writers are based on characters, which can have varying widths depending on the character set. • ASCII and ISO Latin-1 use one-byte characters. Unicode uses two-byte characters • Since characters are ultimately composed of bytes, readers take their input from streams. • However, they convert those bytes into chars according to a specified encoding format before passing them along. • Similarly, writers convert chars to bytes according to a specified encoding before writing them onto some underlying stream. • I/O with character streams is no more complicated than I/O with byte streams. • All character stream classes are descended from Reader and Writer. • The most important reason for the Reader and Writer hierarchies is for internationalization. Character Streams
  • 24. © [email protected] 24 • The FileReader class creates a Reader that you can use to read the contents of a file. • Reading from file • FileReader(String filePath) • FileReader(File fileObj) • Writing to File • FileWriter(String fileName) • FileWriter(String fileName, boolean append) • If append is true, then the file is appended not overwritten FileReader and FileWriter
  • 25. © [email protected] 25 FileReader inputStream = null; FileWriter outputStream = null; try { inputStream = new FileReader(“file1.txt"); outputStream = new FileWriter(“file2.txt"); int c; while ((c = inputStream.read()) != -1) { outputStream.write(c); } } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } Note: In, Character Copy the int variable holds a character value in its last 16 bits; In Bytes Copy, the int variable holds a byte value in its last 8 bits.
  • 26. © [email protected] 26 BufferedReader inputStream = null; PrintWriter outputStream = null; try { inputStream = new BufferedReader(new FileReader("xanadu.txt")); outputStream = new PrintWriter(new FileWriter("characteroutput.txt")); String l; while ((l = inputStream.readLine()) != null) { outputStream.println(l); } } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } Buffered Reader and Writer We can wrap the FileWriter object to the Buffered Writer to achieve higher performance Eg. PrintWriter outputStream = new PrintWriter(new BufferedWriter(new FileWriter(file)));
  • 27. © [email protected] 27 • File input and output streams require you to start reading or writing at the beginning of a file and then read or write the file in order • Sometimes, however, you need to read parts of a file in a more or less random order, where the data near the beginning of the file isn't necessarily read before the data nearer the end. • Other times you need to both read and write the same file • Random-access files can be read from or written to or both from a particular byte position in the file. • The RandomAccessFile class implements both the DataInput and DataOutput interfaces. Therefore, reads and writes use methods exactly like methods of the DataInputStream and DataOutputStream. • Constructor • RandomAccessFile(File fileObj, String access) • RandomAccessFile(String filename, String access) • Access defines the file permission ie. r or rw (also rws/rwd) • Methods • void seek(long newPos) • long getFilePointer() • long length() //find length of file RandomAccessFile
  • 28. © [email protected] 28 //Reading from file RandomAccessFile file = new RandomAccessFile("d:abc.txt", "r"); file.seek(150); byte[] bytes = new byte[23]; file.read(bytes); file.close(); System.out.println(new String(bytes)); //Writing to file String data=“Java Rocks!!!”; RandomAccessFile file = new RandomAccessFile(“d:abc.txt”, "rw"); file.seek(22); file.write(data.getBytes()); file.close() Example
  • 29. © [email protected] 29 • Most of the classes defined by java.io operate on streams, the File class does not. • File deals directly with files and the file system. That is, the File class does not specify how information is retrieved from or stored in files; it describes the properties of a file itself. • File object is used to obtain or manipulate the information associated with a disk file, such as the permissions, time, date, and directory path, and to navigate subdirectory hierarchies. • We should use standard stream input/output classes to direct access for reading and writing file data File (java.io.File)
  • 30. © [email protected] 30 • Constructor • File(String directoryPath) • File(String directoryPath, String filename) • To Get Paths • getAbsolutePath(), getPath(), getParent(), getCanonicalPath() • To Check Files • isFile(), isDirectory(), exists() • To Get File Properties • getName(), length(), isAbsolute(), lastModified(), isHidden() //length in bytes • To Get File Permissions • canRead(), can Write(), canExecute() • To Know Storage information • getFreeSpace(), getUsableSpace(), getTotalSpace() • Utility Functions • Boolean createNewFile() • Boolean renameTo(File nf); renames the file and returns true if success • Boolean delete(); deletes the file represented by path of file (also delete directory if its empty) • Boolean setLastModified(long ms) sets timestamp(Jan 1, 1970 UTC as a start time) • Boolean setReadOnly() to mark file as readable (also can be done writable, and executable.)
  • 31. © [email protected] 31 • You can create an instance of File from a String pathname: • File fooFile = new File( "/tmp/foo.txt" ); • File fooFile = new File( "/tmp", "foo.txt" ); • File barDir = new File( "/tmp/bar" ); • You can also create a file with a relative path: • File f = new File( "foo" ); • In this case, Java works relative to the current directory of the Java interpreter. Can find the current directory by checking the user.dir property in the System Properties list: System.getProperty("user.dir")); • The static method createTempFile(string prefix, string suffix ) , creates a file in a specified location using an automatically generated unique name • Use int compareTo(File f) to compare two files. • Use the static method File.listRoots( ) to know about all the top-level directories, such as C:, D: etc • File[] drives = File.listRoots( );
  • 32. © [email protected] 32 • A directory is a File that contains a list of other files and directories. • When you create a File object that is directory, the isDirectory( ) method will return true and you can use list() method • Methods • String[] list( ) extract the list of files and directories inside • File[] listFiles() return array of File objects • File[] listFiles(FileFilter ff) return File that satisfied FileFilter which uses Boolean accept(File path) that match path argument • Boolean mkdir()/mkdirs() create specify directory / with path Directory
  • 33. © [email protected] 33 String dirname = "/java"; File f1 = new File(dirname); if (f1.isDirectory()) { System.out.println(“Reading Directory = " + dirname); String s[] = f1.list(); for (int i=0; i < s.length; i++) { File f = new File(dirname + "/" + s[i]); if (f.isDirectory()) System.out.println(s[i] + " is a directory"); else System.out.println(s[i] + " is a file"); } Code
  • 35. © [email protected] 35 • How is a -1 that appears as a part of data to be distinguished from a -1 indicating end of stream? • Read() function doesn’t return a byte; its signature says it return an integers. This int is not a java byte with value between -128 to +127 but a more general byte with value between 0 and 255. Hence -1 can be easily distinguished. • How conversion? • Since bytes have such a small range, they're often converted to ints in calculations and method invocations. • Casting from an int to a byte—for that matter, casting from any wider integer type to a narrower type—takes place through truncation of the high-order bytes. • This means that as long as the value of the wider type can be expressed in the narrower type, the value is not changed. The int 127 cast to a byte still retains the value 127. On the other hand, if the int value is too large for a byte, strange things happen. So, 128 will be 10000000 is -127 How? (absolute value of –ve number is found by taking complement and adding 1 to it) • How characters are treated? • Since computers only really understand numbers, characters are encoded by matching each character in a given script to a particular number. For example, in the common ASCII encoding, the character A is mapped to the number 65; • ASCII, the American Standard Code for Information Interchange, is a seven-bit character set. Thus it defines 27 or 128 different characters whose numeric values range from to 127. These characters are sufficient for handling most of American English • How Character Stream work? • Character-oriented data in Java is primarily composed of the char primitive data type . you need to understand chars to understand how reader and writer works. • In Java, a char is a two-byte, unsigned integer, the only unsigned type in Java. Thus, possible char values range from 0 to 65,535. Chars may be assigned to by using int literals in this range • chars may also be assigned to by using char literals; that is, the character itself enclosed in single quotes.
  • 36. © [email protected] 36 • difference between an 8-bit byte and a 32-bit int ? • is insignificant for a single number • it can be very significant when several thousand to several million numbers are read. • In fact, a single byte still takes up four bytes of space inside the Java virtual machine, but • byte array only occupies the amount of space it actually needs. • The virtual machine includes special instructions for operating on byte arrays, but • does not include any instructions for operating on single bytes. They're just promoted to int. How JVM treats byte & byte[]
  • 37. © [email protected] 37 • You often want to look for a particular kind of file—for example, text files, image files etc. • Need a FilenameFilter or FileFilter object that specifies which files you'll accept • FilenameFilter is an interface with method • Public abstract Boolean accept(File dir,String name) • FileFilter is an interface with method • Public abstract Boolean accept(File dir) • public File[] listFiles(FilenameFilter filter) • public File[] listFiles(FileFilter filter) public class ImageFilter implements FilenameFilter { public boolean accept(File directory, String name) { if (name.endsWith(".jpg")) return true; if (name.endsWith(".jpeg")) return true; return false; } //public class HTMLFilter implements FileFilter { //public boolean accept(File pathname) { //if (pathname.getName().endsWith(".html")) return true; } File dir = new File("/public/picture/"); File[] imgs = dir.listFiles(new ImageFilter()); Read Filtered Files only
  • 38. © [email protected] 38 • Open the file Character Chart