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

PPTX
Introduction to OOP in Python
Aleksander Fabijan
 
PDF
Python file handling
Prof. Dr. K. Adisesha
 
PPTX
Operator overloading
Ramish Suleman
 
PPTX
Python basics
RANAALIMAJEEDRAJPUT
 
PDF
Files in java
Muthukumaran Subramanian
 
PDF
Python functions
Prof. Dr. K. Adisesha
 
PPTX
Exception handling
PhD Research Scholar
 
PPTX
Threads in JAVA
Haldia Institute of Technology
 
Introduction to OOP in Python
Aleksander Fabijan
 
Python file handling
Prof. Dr. K. Adisesha
 
Operator overloading
Ramish Suleman
 
Python basics
RANAALIMAJEEDRAJPUT
 
Python functions
Prof. Dr. K. Adisesha
 
Exception handling
PhD Research Scholar
 

What's hot (20)

PPTX
Vectors in Java
Abhilash Nair
 
PDF
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Edureka!
 
PPTX
Core java complete ppt(note)
arvind pandey
 
PDF
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
PPT
Input output streams
Parthipan Parthi
 
PDF
Generics
Ravi_Kant_Sahu
 
PPT
9. Input Output in java
Nilesh Dalvi
 
PDF
Java Linked List Tutorial | Edureka
Edureka!
 
PDF
input/ output in java
sharma230399
 
PPTX
Union in c language
tanmaymodi4
 
PPT
programming with python ppt
Priyanka Pradhan
 
PPTX
Object oriented programming in python
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Loops in Python
AbhayDhupar
 
PPTX
Functions in Python
Kamal Acharya
 
PPTX
Pointers in c++
Vineeta Garg
 
PDF
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
PDF
Applets
Prabhakaran V M
 
PPTX
Object oriented programming
baabtra.com - No. 1 supplier of quality freshers
 
PPT
Java layoutmanager
Arati Gadgil
 
Vectors in Java
Abhilash Nair
 
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Edureka!
 
Core java complete ppt(note)
arvind pandey
 
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
Input output streams
Parthipan Parthi
 
Generics
Ravi_Kant_Sahu
 
9. Input Output in java
Nilesh Dalvi
 
Java Linked List Tutorial | Edureka
Edureka!
 
input/ output in java
sharma230399
 
Union in c language
tanmaymodi4
 
programming with python ppt
Priyanka Pradhan
 
Object oriented programming in python
baabtra.com - No. 1 supplier of quality freshers
 
Loops in Python
AbhayDhupar
 
Functions in Python
Kamal Acharya
 
Pointers in c++
Vineeta Garg
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
Java layoutmanager
Arati Gadgil
 
Ad

Viewers also liked (20)

PDF
Java Course 8: I/O, Files and Streams
Anton Keks
 
PDF
Java I/O
Jussi Pohjolainen
 
PPT
Java Input Output and File Handling
Sunil OS
 
PPTX
Understanding java streams
Shahjahan Samoon
 
PPT
Various io stream classes .47
myrajendra
 
PPT
Java IO Package and Streams
babak danyal
 
PPTX
Handling I/O in Java
Hiranya Jayathilaka
 
PPS
Introduction to class in java
kamal kotecha
 
PPT
Java tutorial PPT
Intelligo Technologies
 
PPT
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Don Bosco BSIT
 
PPT
Unit v
snehaarao19
 
PDF
Java IO
UTSAB NEUPANE
 
PPT
Character stream classes .52
myrajendra
 
PPT
Byte stream classes.49
myrajendra
 
DOCX
Nested classes in java
Richa Singh
 
PPT
Inner classes9 cm604.28
myrajendra
 
PPTX
Inner classes
DraftKing Zohaib
 
PDF
I/O in java Part 1
ashishspace
 
PPTX
L21 io streams
teach4uin
 
Java Course 8: I/O, Files and Streams
Anton Keks
 
Java Input Output and File Handling
Sunil OS
 
Understanding java streams
Shahjahan Samoon
 
Various io stream classes .47
myrajendra
 
Java IO Package and Streams
babak danyal
 
Handling I/O in Java
Hiranya Jayathilaka
 
Introduction to class in java
kamal kotecha
 
Java tutorial PPT
Intelligo Technologies
 
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Don Bosco BSIT
 
Unit v
snehaarao19
 
Java IO
UTSAB NEUPANE
 
Character stream classes .52
myrajendra
 
Byte stream classes.49
myrajendra
 
Nested classes in java
Richa Singh
 
Inner classes9 cm604.28
myrajendra
 
Inner classes
DraftKing Zohaib
 
I/O in java Part 1
ashishspace
 
L21 io streams
teach4uin
 
Ad

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

PPT
Java development development Files lectur6.ppt
rafeakrafeak
 
PDF
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
cuchuoi83ne
 
PPTX
IOStream.pptx
HindAlmisbahi
 
PDF
IOstreams hgjhsgfdjyggckhgckhjxfhbuvobunciu
akinbhattarai1
 
PPTX
CHAPTER 5 mechanical engineeringasaaa.pptx
SadhilAggarwal
 
PPT
Io stream
Parthipan Parthi
 
PDF
Advanced programming ch2
Gera Paulos
 
PPTX
Java I/O
Jayant Dalvi
 
PDF
CSE3146-ADV JAVA M2.pdf
VithalReddy3
 
PPTX
Javaiostream
Manav Prasad
 
PPTX
IO Programming.pptx all informatiyon ppt
nandinimakwana22cse
 
PPTX
Java Tutorial Lab 6
Berk Soysal
 
PDF
javaiostream
Arjun Shanka
 
PDF
Javaiostream
Tien Nguyen
 
PDF
Programming language JAVA Input output opearations
2025183005
 
PDF
Apache Arrow Workshop at VLDB 2019 / BOSS Session
Wes McKinney
 
PPT
Using Input Output
raksharao
 
PPTX
Java input output package
Sujit Kumar
 
PPTX
Files io
Narayana Swamy
 
PDF
Basic IO
Ravi_Kant_Sahu
 
Java development development Files lectur6.ppt
rafeakrafeak
 
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
cuchuoi83ne
 
IOStream.pptx
HindAlmisbahi
 
IOstreams hgjhsgfdjyggckhgckhjxfhbuvobunciu
akinbhattarai1
 
CHAPTER 5 mechanical engineeringasaaa.pptx
SadhilAggarwal
 
Io stream
Parthipan Parthi
 
Advanced programming ch2
Gera Paulos
 
Java I/O
Jayant Dalvi
 
CSE3146-ADV JAVA M2.pdf
VithalReddy3
 
Javaiostream
Manav Prasad
 
IO Programming.pptx all informatiyon ppt
nandinimakwana22cse
 
Java Tutorial Lab 6
Berk Soysal
 
javaiostream
Arjun Shanka
 
Javaiostream
Tien Nguyen
 
Programming language JAVA Input output opearations
2025183005
 
Apache Arrow Workshop at VLDB 2019 / BOSS Session
Wes McKinney
 
Using Input Output
raksharao
 
Java input output package
Sujit Kumar
 
Files io
Narayana Swamy
 
Basic IO
Ravi_Kant_Sahu
 

Recently uploaded (20)

PDF
Become an Agentblazer Champion Challenge
Dele Amefo
 
PDF
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
PPTX
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
PDF
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
QAware GmbH
 
PDF
Solar Panel Installation Guide – Step By Step Process 2025.pdf
CRMLeaf
 
PDF
PFAS Reporting Requirements 2026 Are You Submission Ready Certivo.pdf
Certivo Inc
 
PPT
Activate_Methodology_Summary presentatio
annapureddyn
 
PDF
Exploring AI Agents in Process Industries
amoreira6
 
PDF
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
University of Rennes, INSA Rennes, Inria/IRISA, CNRS
 
PDF
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
PPTX
Role Of Python In Programing Language.pptx
jaykoshti048
 
PPTX
TestNG for Java Testing and Automation testing
ssuser0213cb
 
PDF
49784907924775488180_LRN2959_Data_Pump_23ai.pdf
Abilash868456
 
PPTX
oapresentation.pptx
mehatdhavalrajubhai
 
PDF
Build Multi-agent using Agent Development Kit
FadyIbrahim23
 
PPTX
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
PDF
Community & News Update Q2 Meet Up 2025
VictoriaMetrics
 
PDF
The Role of Automation and AI in EHS Management for Data Centers.pdf
TECH EHS Solution
 
PPTX
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
PDF
Why Use Open Source Reporting Tools for Business Intelligence.pdf
Varsha Nayak
 
Become an Agentblazer Champion Challenge
Dele Amefo
 
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
QAware GmbH
 
Solar Panel Installation Guide – Step By Step Process 2025.pdf
CRMLeaf
 
PFAS Reporting Requirements 2026 Are You Submission Ready Certivo.pdf
Certivo Inc
 
Activate_Methodology_Summary presentatio
annapureddyn
 
Exploring AI Agents in Process Industries
amoreira6
 
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
University of Rennes, INSA Rennes, Inria/IRISA, CNRS
 
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
Role Of Python In Programing Language.pptx
jaykoshti048
 
TestNG for Java Testing and Automation testing
ssuser0213cb
 
49784907924775488180_LRN2959_Data_Pump_23ai.pdf
Abilash868456
 
oapresentation.pptx
mehatdhavalrajubhai
 
Build Multi-agent using Agent Development Kit
FadyIbrahim23
 
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
Community & News Update Q2 Meet Up 2025
VictoriaMetrics
 
The Role of Automation and AI in EHS Management for Data Centers.pdf
TECH EHS Solution
 
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
Why Use Open Source Reporting Tools for Business Intelligence.pdf
Varsha Nayak
 

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