SlideShare a Scribd company logo
MODULE – 2
Multithreading in Java
1
MODULE – 2
Input output operation using Java
Input/output operation in java (java.io), Streams and the new I/O capabilities,
understanding streams, working with file object, file I/O basics, reading and
writing to files, buffer and buffer management, read/write operations with file
channel, serializing objects, observer and observable interfaces.
2
Syllabus
• Introduction of I/O operations
• Stream
• The java.io.* package
• File operations
• Channel and Buffer usages
• Serialization of network objects
• Observer and Observable interfaces (Knowledge level)
3
Contents
4
I/O Introduction
• I/O = Input/Output
• In this context it is input to and output from programs
• Input can be from keyboard or a file
• Output can be to display (screen) or a file
• Advantages of file I/O
• permanent copy
• output from one program can be input to another
• input can be automated (rather than entered manually)
Binary Versus Text Files
• All data and programs are ultimately just zeros and ones
• each digit can have one of two values, hence binary
• bit is one binary digit
• byte is a group of eight bits
• Text files: the bits represent printable characters
• one byte per character for ASCII, the most common code
• for example, Java source files are text files
• so is any file created with a "text editor"
• Binary files: the bits represent other types of encoded information, such as
executable instructions or numeric data
• these files are easily read by the computer but not humans
• they are not "printable" files
• actually, you can print them, but they will be unintelligible
• "printable" means "easily readable by humans when printed"
Text file: an example
[unix: od –w8 –bc <file>]
[http://www.muquit.com/muquit/software/hod/hod.html for a Windows tool]
127 smiley
faces
0000000 061 062 067 011 163 155 151 154
1 2 7 t s m i l
0000010 145 171 012 146 141 143 145 163
e y n f a c e s
0000020 012
n
Binary file: an example [a .class file]
0000000 312 376 272 276 000 000 000 061
312 376 272 276 0 0 0 1
0000010 000 164 012 000 051 000 062 007
0 t n 0 ) 0 2 a
0000020 000 063 007 000 064 010 000 065
0 3 a 0 4 b 0 5
0000030 012 000 003 000 066 012 000 002
n 0 003 0 6 n 0 002
...
0000630 000 145 000 146 001 000 027 152
0 e 0 f 001 0 027 j
0000640 141 166 141 057 154 141 156 147
a v a / l a n g
0000650 057 123 164 162 151 156 147 102
/ S t r i n g B
9
File Class
• File class describes the properties of a file/directory.
• A 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.
• An absolute file name (full name) contains a file name with its complete path and drive letter.
For example, c:bookswelcome.pdf
• A relative file is in relation to the current working directory.
For example, welcome.pdf
File Class
• The file class is a wrapper class for the file name and its directory path.
for example,
new File(“c:book”) , it creates a File object for the directory c:book
new File(“c:booktest.dat”) , it creates a File object for the file c:booktest.dat
• The following constructors can be used to create File objects:
• File(String directoryPath)
• File(String directoryPath, String filename)
• File(File dirObj, String filename)
• File(URI uriObj)
• File class does not contain the methods for reading and writing file contents.
File Class, methods
• Boolean isFile()
• Boolean isDirectory()
• Boolean isHidden()
• Boolean exists()
• Boolean canRead()
• Boolean canWrite()
• String getName()
• String getPath()
• String getAbsolutePath()
File Class
• The file class is a wrapper class for the file name and its directory path.
for example,
new File(“c:book”) , it creates a File object for the directory c:book
new File(“c:booktest.dat”) , it creates a File object for the file c:booktest.dat
• The following constructors can be used to create File objects:
• File(String directoryPath)
• File(String directoryPath, String filename)
• File(File dirObj, String filename)
• File(URI uriObj)
• File class does not contain the methods for reading and writing file contents.
Exercise 1 : Demonstrating File
// Demonstrate File
class,constructors,methods
import java.io.File;
class FileDemo {
static void print(String s) {
System.out.println(s);
}
public static void main(String args[]) {
File f1 = new File("/java/COPYRIGHT");
print("File Name: " + f1.getName());
print("Path: " + f1.getPath());
print("Abs Path: " + f1.getAbsolutePath());
print("Parent: " + f1.getParent());
print(f1.exists() ? "exists" : "does not
exist");
p("File last modified: " + f1.lastModified());
p("File size: " + f1.length() + " Bytes");
}
}
File class , for a folder/directory
• A directory in Java is treated simply as a File with one additional property—a list of filenames that
can be examined by the list( ) method.
Exercise2 : Demonstrating directories
// Demonstrate Folder // Using directories.
import java.io.File;
class DirList {
public static void main(String args[]) {
String dirname = "/java";
File f1 = new File(dirname);
if (f1.isDirectory()) {
System.out.println("Directory of " + 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");
}
}
} else {
System.out.println(dirname + " is not a
directory");
}}}
Reading and Writing Files
• In Java, all files are byte-oriented, and java provides methods to read and write bytes from
and to a file.
• Java allows us to wrap a byte-oriented file stream within a character-based object.
• We can use Scanner and PrintWriter class to read and write files.
PrintWriter Class
• Character-based class.
• Using a character-based class for console output makes it easier to internationalize the
program.
• PrintWriter(OutputStream outputstream, boolean flushOnNewline)
where Outputstream is an object of type OutputStream.
• flushOnNewLine controls whether Java flushes the output stream every time a println()
method is called.
• If flushOnLine is true, flushing automatically takes place.
• If false, flushing is not automatic.
PrintWriter Demo
Import java.io.*;
public class PrintWriterDemo {
public static void main(String[] args) {
PrintWriter pw = new PrintWriter(System.out,true);
pw.println(“using print writer object”);
int i=-7;
pw.println(i);
double d=4.5;
pw.println(d);
}
}
Scanner Class
• To read from the keyboard, we create a Scanner as follows:
Scanner sc=new Scanner(System.in);
• To read from a file, create a Scanner for a file, as follows:
Scanner sc=new Scanner(new File(filename));
Scanner Methods:
next()
nextLine()
nextInt()
……
21
Streams
• Stream: an object that either delivers data to its
destination (screen, file, etc.) or that takes data from a
source (keyboard, file, etc.)
• it acts as a buffer between the data source and
destination
• Input stream: a stream that provides input to a program
• System.in is an input stream
• Output stream: a stream that accepts output from a
program
• System.out is an output stream
• A stream connects a program to an I/O object
• System.out connects a program to the screen
• System.in connects a program to the keyboard
Input stream
output stream
Streams Types
• Java defines two different types of Streams-
ByteStream
CharacterStream
ByteStreams
• Works with bytes and
binary objects
• InputStream class for read
operation
• OutputStream class for
write operation
CharacterStreams
• Works with characters and
strings
• Reader class for read
operation
• Writer for write operation
Text File I/O
• Important classes for text file output (to the file)
• PrintWriter
• FileOutputStream [or FileWriter]
• Important classes for text file input (from the file):
• BufferedReader
• FileReader
• FileOutputStream and FileReader take file names as arguments.
• PrintWriter and BufferedReader provide useful methods for easier
writing and reading.
• Usually need a combination of two classes
• To use these classes your program needs a line like the following:
import java.io.*;
Byte Streams
• Programs use byte streams to perform input and output of 8-bit bytes
• Byte streams are defined by using two class hierarchies
• At the top, there are two abstract classes : InputStream and OutputStream
• The abstract classes InputStream and OutputStream define several key methods that the
other stream classes implement
• Two of the most important methods are read() and write() , which respectively read and write
bytes of data
• Both methods are declared as abstract inside InputStream and OutputStream
• It is important that we have used a finally block to guarantee that both streams will be closed
even if an error occurs. This helps resource leaks.
• When we call the close() , it clears buffer by performing the write operation to the destination
and then closes the stream.
Byte Stream classes
The following are the child classes for InputStream and OutputStream
Byte Stream : InputStream and OutputStream classes
The following are the child classes for InputStream and OutputStream.
BufferedInputStream : contain methods to read from input stream buffer
BufferOutputStream : to write
DataInputStream : contain methods for reading the Java standard data types
DataOutputStream : contain methods for writing the Java standard data types
FileInputStream : Input stream that reads from a file
FileOutputStream : output stream the writes to a file
InputStream : abstract class that describes stream inputs
OutputStream : abstract class that describes stream outputs
PrintStream : output stream that contains print() and println()
PipedInputStream : Input pipe
PipedOutputStream : Output pipe
Byte Stream : InputStream Methods
The following are the methods for InputStream.
int available()
void close()
void mark(int numbytes)
int read()
int read(byte buffer[])
void reset()
Byte Stream : OutputStream Methods
The following are the methods for OutputStream.
void close()
void flush()
void write(int b)
void write(byte[] buffer)
void write(byte[] buffer, int offset, int numBytes)
Byte Stream : File operation
• FileInputStream and FileOutputStream are stream classes which create streams linked to
files.
• Constructor
• FileInputStream(String filename) throws FileNotFoundException
• FileInputStream(File fname) throws FileNotFoundException
• FileOutputStream(String filename) throws FileNotFoundException
• FileOutputStream(File fname) throws FileNotFoundException
• FileOutputStream(String filename, boolean append) throws FileNotFoundException
• FileOutputStream(File fname, boolean) throws FileNotFoundException
Byte Stream : File operation
• To read from a file , we can use read() that is defined within FileInputStream
• int read() throws IOException
• Each time read() is called, it reads a single byte from the file and returns the byte as an
integer value.
• To write a file, we can use the write() method defined by FileOutputStream.
• void write(int bytevalue) throws IOException
Byte Stream : copying a file , send source and target names using command line argument
import java.io.*;
public class Test {
public static void main(String[] args) throws IOException {
int i; FileInputStream fin=null; FileOutputStream fout=null;
fin = new FileInputStream(args[0]); fout=new FileOutputStream(args[1]);
try {
while((i=fin.read())!=-1) {
fout.write(i); }
}catch(Exception e) { System.out.println(“File error”); }
System.out.println(“one File copied”);
fin.close(); fout.close(); }}
Character Streams
• Programs use character streams to perform input and output of 16-bit Unicodes that java
supports.
• Character streams are defined by using two class hierarchies
• At the top, there are two abstract classes : Reader and Writer
• The abstract classes Reader and Writer define several key methods that the other character
classes implement
Character Streams : Reader Class
• The abstract classes Reader define several key methods that the other character classes
implement.
• The subclasses those implements the method of Reader are
1. BufferedReader : read characters from buffer
2. CharArrayReader : read characters from character array
3. FileReader : read characters from the file
4. FilterReader : read characters from the character input stream
5. InputStreamReader : converts bytes to character
6. PipedReader : read characters from a piped output stream
7. StringReader : read characters from a string
Character Streams : Reader Methods
• The abstract classes Reader define several key methods that the other character classes
implement.
• Methods declared abstract in Reader classes are :
• int read()
• int read(char[] buffer)
• int read(char[] buffer, int loc, int nchars)
• void reset()
• void close()
Character Streams : Writer Class
• The abstract classes Writer define several key methods that the other character classes
implement.
• The subclasses those implements the method of Writer are
1. BufferedWriter : write characters to buffer
2. FileWriter : write characters to file
3. CharArrayWriter : write characters to the character array
4. OutputStreamWriter : converts bytes to character
5. PipedWriter : write characters to a piped output stream
6. StringWriter : write characters to a string
Character Streams : Writer Methods
• The abstract classes Writer define several key methods that the other character classes
implement.
• Methods declared abstract in Writer classes are :
• void write()
• void write(int i)
• void write(char[] buffer, int loc, int nchars)
• void flush()
• void close()
38
NIO api : introduces channel and Buffer
Drawbacks of traditional java.io.*
• Lacks some important functionality , such as copy() not available in File class
• Defined many methods that returns boolean. In case of error , instead of exception, method
returns false.
• A limited set of file attributes was provided.
Features of java.nio.*
• Added with java 6/ jdk 6
• Stands for non blocking i/o
• Bulk access to raw bytes
• Bidirectional channels
• Introduces three new concepts : Channel, Buffer and Selector
Channel
• The channel is where the data comes from.
• The channel object is an object that connect to a file .
• A channel can write the buffer to the medium or can read data from that medium to a buffer.
• In Java , Channel is an interface
• Implemented by FileChannel, DatagramChannel, SocketChannel
Channel : FileChannel
• A FileChannel can be mapped to a memory array for direct access. This allows for much
faster operation than accessing to the disk directly.
• It is built on native features provided by the different operating system and this is the reason
why the concrete implementation of FileChannel are hidden just bcz they are different
depending on the machine we are working on.
• There are 3 modes of operation by a channel
• READ_ONLY
• READ_WRITE
• PRIVATE
Buffer
• A buffer can be seen as a space in memory. It can reside in the main memory of the JVM.
• A buffer object has 3 properties:
• a capacity = the size of the backing array.
• a current position that can be seen as cursor. All the read and the write operations are made
to or from the current position.
• a limit which is the last position in memory seen by this buffer.
• A buffer supports 4 operations:
• rewind: clears the mark and sets the current position to 0.
• reset: sets the current position to the previously set mark. This is the companion method of
the mark method.
• flip: sets the limit to the current position and rewinds the buffer.
• clear: clears the buffer.
Buffer
• Buffer is an abstract class in java.
• Extended by ByteBuffer, CharBuffer,
Exercise : Writing content to a file using Buffers and Channels
• Steps:
• Create a ByteBuffer.
• use the putXXX() method to write data.
• have our FileChannel to write the ByteBuffer to a file.
45
Serialization
Serializable Interface
Serialization Example
Serialization Example
Serialization Example
Exercise
Observer and Observable Interface
The Java language supports the MVC architecture with two classes:
Observer : Any object that wishes to be notified when the state of
another object changes
Observable : Any object whose state may be of interest, and in
whom another object may register an interest.
52
53
Module – 2 Completed
Ad

Recommended

Java Day-6
Java Day-6
People Strategists
 
IOStream.pptx
IOStream.pptx
HindAlmisbahi
 
L21 io streams
L21 io streams
teach4uin
 
Java I/O
Java I/O
Jayant Dalvi
 
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
hungvidien123
 
IO Programming.pptx all informatiyon ppt
IO Programming.pptx all informatiyon ppt
nandinimakwana22cse
 
Input output files in java
Input output files in java
Kavitha713564
 
File Handling in Java.pdf
File Handling in Java.pdf
SudhanshiBakre1
 
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
noonoboom
 
Java Tutorial Lab 6
Java Tutorial Lab 6
Berk Soysal
 
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
cuchuoi83ne
 
Chapter 6
Chapter 6
siragezeynu
 
chapter 2(IO and stream)/chapter 2, IO and stream
chapter 2(IO and stream)/chapter 2, IO and stream
amarehope21
 
ch09.ppt
ch09.ppt
NiharikaDubey17
 
Io streams
Io streams
Elizabeth alexander
 
Basic i/o & file handling in java
Basic i/o & file handling in java
JayasankarPR2
 
File Input and output.pptx
File Input and output.pptx
cherryreddygannu
 
Programming language JAVA Input output opearations
Programming language JAVA Input output opearations
2025183005
 
File Handling.pptx
File Handling.pptx
PragatiSutar4
 
Java IO
Java IO
UTSAB NEUPANE
 
Files that are designed to be read by human beings
Files that are designed to be read by human beings
ManishKumar475693
 
IOstreams hgjhsgfdjyggckhgckhjxfhbuvobunciu
IOstreams hgjhsgfdjyggckhgckhjxfhbuvobunciu
akinbhattarai1
 
Input/Output Exploring java.io
Input/Output Exploring java.io
NilaNila16
 
Advanced programming ch2
Advanced programming ch2
Gera Paulos
 
CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptx
SadhilAggarwal
 
Java IO Stream, the introduction to Streams
Java IO Stream, the introduction to Streams
ranganadh6
 
File Input and Output in Java Programing language
File Input and Output in Java Programing language
BurhanKhan774154
 
Javaio
Javaio
Jaya Jeswani
 
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
João Esperancinha
 
60 Years and Beyond eBook 1234567891.pdf
60 Years and Beyond eBook 1234567891.pdf
waseemalazzeh
 

More Related Content

Similar to CSE3146-ADV JAVA M2.pdf (20)

Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
noonoboom
 
Java Tutorial Lab 6
Java Tutorial Lab 6
Berk Soysal
 
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
cuchuoi83ne
 
Chapter 6
Chapter 6
siragezeynu
 
chapter 2(IO and stream)/chapter 2, IO and stream
chapter 2(IO and stream)/chapter 2, IO and stream
amarehope21
 
ch09.ppt
ch09.ppt
NiharikaDubey17
 
Io streams
Io streams
Elizabeth alexander
 
Basic i/o & file handling in java
Basic i/o & file handling in java
JayasankarPR2
 
File Input and output.pptx
File Input and output.pptx
cherryreddygannu
 
Programming language JAVA Input output opearations
Programming language JAVA Input output opearations
2025183005
 
File Handling.pptx
File Handling.pptx
PragatiSutar4
 
Java IO
Java IO
UTSAB NEUPANE
 
Files that are designed to be read by human beings
Files that are designed to be read by human beings
ManishKumar475693
 
IOstreams hgjhsgfdjyggckhgckhjxfhbuvobunciu
IOstreams hgjhsgfdjyggckhgckhjxfhbuvobunciu
akinbhattarai1
 
Input/Output Exploring java.io
Input/Output Exploring java.io
NilaNila16
 
Advanced programming ch2
Advanced programming ch2
Gera Paulos
 
CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptx
SadhilAggarwal
 
Java IO Stream, the introduction to Streams
Java IO Stream, the introduction to Streams
ranganadh6
 
File Input and Output in Java Programing language
File Input and Output in Java Programing language
BurhanKhan774154
 
Javaio
Javaio
Jaya Jeswani
 
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
noonoboom
 
Java Tutorial Lab 6
Java Tutorial Lab 6
Berk Soysal
 
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
cuchuoi83ne
 
chapter 2(IO and stream)/chapter 2, IO and stream
chapter 2(IO and stream)/chapter 2, IO and stream
amarehope21
 
Basic i/o & file handling in java
Basic i/o & file handling in java
JayasankarPR2
 
File Input and output.pptx
File Input and output.pptx
cherryreddygannu
 
Programming language JAVA Input output opearations
Programming language JAVA Input output opearations
2025183005
 
Files that are designed to be read by human beings
Files that are designed to be read by human beings
ManishKumar475693
 
IOstreams hgjhsgfdjyggckhgckhjxfhbuvobunciu
IOstreams hgjhsgfdjyggckhgckhjxfhbuvobunciu
akinbhattarai1
 
Input/Output Exploring java.io
Input/Output Exploring java.io
NilaNila16
 
Advanced programming ch2
Advanced programming ch2
Gera Paulos
 
CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptx
SadhilAggarwal
 
Java IO Stream, the introduction to Streams
Java IO Stream, the introduction to Streams
ranganadh6
 
File Input and Output in Java Programing language
File Input and Output in Java Programing language
BurhanKhan774154
 

Recently uploaded (20)

Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
João Esperancinha
 
60 Years and Beyond eBook 1234567891.pdf
60 Years and Beyond eBook 1234567891.pdf
waseemalazzeh
 
4th International Conference on Computer Science and Information Technology (...
4th International Conference on Computer Science and Information Technology (...
ijait
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
djiceramil
 
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
dayananda54
 
3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt
engaash9
 
Modern multi-proposer consensus implementations
Modern multi-proposer consensus implementations
François Garillot
 
Engineering Mechanics Introduction and its Application
Engineering Mechanics Introduction and its Application
Sakthivel M
 
How Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdf
Mina Anis
 
Great power lithium iron phosphate cells
Great power lithium iron phosphate cells
salmankhan835951
 
Water demand - Types , variations and WDS
Water demand - Types , variations and WDS
dhanashree78
 
Structural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant Conversion
DanielRoman285499
 
Impurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptx
dhanashree78
 
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Yannis
 
ElysiumPro Company Profile 2025-2026.pdf
ElysiumPro Company Profile 2025-2026.pdf
info751436
 
Fundamentals of Digital Design_Class_12th April.pptx
Fundamentals of Digital Design_Class_12th April.pptx
drdebarshi1993
 
OCS Group SG - HPHT Well Design and Operation - SN.pdf
OCS Group SG - HPHT Well Design and Operation - SN.pdf
Muanisa Waras
 
IntroSlides-June-GDG-Cloud-Munich community [email protected]
IntroSlides-June-GDG-Cloud-Munich community [email protected]
Luiz Carneiro
 
Machine Learning - Classification Algorithms
Machine Learning - Classification Algorithms
resming1
 
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
João Esperancinha
 
60 Years and Beyond eBook 1234567891.pdf
60 Years and Beyond eBook 1234567891.pdf
waseemalazzeh
 
4th International Conference on Computer Science and Information Technology (...
4th International Conference on Computer Science and Information Technology (...
ijait
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
djiceramil
 
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
dayananda54
 
3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt
engaash9
 
Modern multi-proposer consensus implementations
Modern multi-proposer consensus implementations
François Garillot
 
Engineering Mechanics Introduction and its Application
Engineering Mechanics Introduction and its Application
Sakthivel M
 
How Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdf
Mina Anis
 
Great power lithium iron phosphate cells
Great power lithium iron phosphate cells
salmankhan835951
 
Water demand - Types , variations and WDS
Water demand - Types , variations and WDS
dhanashree78
 
Structural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant Conversion
DanielRoman285499
 
Impurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptx
dhanashree78
 
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Yannis
 
ElysiumPro Company Profile 2025-2026.pdf
ElysiumPro Company Profile 2025-2026.pdf
info751436
 
Fundamentals of Digital Design_Class_12th April.pptx
Fundamentals of Digital Design_Class_12th April.pptx
drdebarshi1993
 
OCS Group SG - HPHT Well Design and Operation - SN.pdf
OCS Group SG - HPHT Well Design and Operation - SN.pdf
Muanisa Waras
 
Machine Learning - Classification Algorithms
Machine Learning - Classification Algorithms
resming1
 
Ad

CSE3146-ADV JAVA M2.pdf

  • 1. MODULE – 2 Multithreading in Java 1 MODULE – 2 Input output operation using Java
  • 2. Input/output operation in java (java.io), Streams and the new I/O capabilities, understanding streams, working with file object, file I/O basics, reading and writing to files, buffer and buffer management, read/write operations with file channel, serializing objects, observer and observable interfaces. 2 Syllabus
  • 3. • Introduction of I/O operations • Stream • The java.io.* package • File operations • Channel and Buffer usages • Serialization of network objects • Observer and Observable interfaces (Knowledge level) 3 Contents
  • 4. 4
  • 5. I/O Introduction • I/O = Input/Output • In this context it is input to and output from programs • Input can be from keyboard or a file • Output can be to display (screen) or a file • Advantages of file I/O • permanent copy • output from one program can be input to another • input can be automated (rather than entered manually)
  • 6. Binary Versus Text Files • All data and programs are ultimately just zeros and ones • each digit can have one of two values, hence binary • bit is one binary digit • byte is a group of eight bits • Text files: the bits represent printable characters • one byte per character for ASCII, the most common code • for example, Java source files are text files • so is any file created with a "text editor" • Binary files: the bits represent other types of encoded information, such as executable instructions or numeric data • these files are easily read by the computer but not humans • they are not "printable" files • actually, you can print them, but they will be unintelligible • "printable" means "easily readable by humans when printed"
  • 7. Text file: an example [unix: od –w8 –bc <file>] [http://www.muquit.com/muquit/software/hod/hod.html for a Windows tool] 127 smiley faces 0000000 061 062 067 011 163 155 151 154 1 2 7 t s m i l 0000010 145 171 012 146 141 143 145 163 e y n f a c e s 0000020 012 n
  • 8. Binary file: an example [a .class file] 0000000 312 376 272 276 000 000 000 061 312 376 272 276 0 0 0 1 0000010 000 164 012 000 051 000 062 007 0 t n 0 ) 0 2 a 0000020 000 063 007 000 064 010 000 065 0 3 a 0 4 b 0 5 0000030 012 000 003 000 066 012 000 002 n 0 003 0 6 n 0 002 ... 0000630 000 145 000 146 001 000 027 152 0 e 0 f 001 0 027 j 0000640 141 166 141 057 154 141 156 147 a v a / l a n g 0000650 057 123 164 162 151 156 147 102 / S t r i n g B
  • 9. 9
  • 10. File Class • File class describes the properties of a file/directory. • A 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. • An absolute file name (full name) contains a file name with its complete path and drive letter. For example, c:bookswelcome.pdf • A relative file is in relation to the current working directory. For example, welcome.pdf
  • 11. File Class • The file class is a wrapper class for the file name and its directory path. for example, new File(“c:book”) , it creates a File object for the directory c:book new File(“c:booktest.dat”) , it creates a File object for the file c:booktest.dat • The following constructors can be used to create File objects: • File(String directoryPath) • File(String directoryPath, String filename) • File(File dirObj, String filename) • File(URI uriObj) • File class does not contain the methods for reading and writing file contents.
  • 12. File Class, methods • Boolean isFile() • Boolean isDirectory() • Boolean isHidden() • Boolean exists() • Boolean canRead() • Boolean canWrite() • String getName() • String getPath() • String getAbsolutePath()
  • 13. File Class • The file class is a wrapper class for the file name and its directory path. for example, new File(“c:book”) , it creates a File object for the directory c:book new File(“c:booktest.dat”) , it creates a File object for the file c:booktest.dat • The following constructors can be used to create File objects: • File(String directoryPath) • File(String directoryPath, String filename) • File(File dirObj, String filename) • File(URI uriObj) • File class does not contain the methods for reading and writing file contents.
  • 14. Exercise 1 : Demonstrating File // Demonstrate File class,constructors,methods import java.io.File; class FileDemo { static void print(String s) { System.out.println(s); } public static void main(String args[]) { File f1 = new File("/java/COPYRIGHT"); print("File Name: " + f1.getName()); print("Path: " + f1.getPath()); print("Abs Path: " + f1.getAbsolutePath()); print("Parent: " + f1.getParent()); print(f1.exists() ? "exists" : "does not exist"); p("File last modified: " + f1.lastModified()); p("File size: " + f1.length() + " Bytes"); } }
  • 15. File class , for a folder/directory • A directory in Java is treated simply as a File with one additional property—a list of filenames that can be examined by the list( ) method.
  • 16. Exercise2 : Demonstrating directories // Demonstrate Folder // Using directories. import java.io.File; class DirList { public static void main(String args[]) { String dirname = "/java"; File f1 = new File(dirname); if (f1.isDirectory()) { System.out.println("Directory of " + 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"); } } } else { System.out.println(dirname + " is not a directory"); }}}
  • 17. Reading and Writing Files • In Java, all files are byte-oriented, and java provides methods to read and write bytes from and to a file. • Java allows us to wrap a byte-oriented file stream within a character-based object. • We can use Scanner and PrintWriter class to read and write files.
  • 18. PrintWriter Class • Character-based class. • Using a character-based class for console output makes it easier to internationalize the program. • PrintWriter(OutputStream outputstream, boolean flushOnNewline) where Outputstream is an object of type OutputStream. • flushOnNewLine controls whether Java flushes the output stream every time a println() method is called. • If flushOnLine is true, flushing automatically takes place. • If false, flushing is not automatic.
  • 19. PrintWriter Demo Import java.io.*; public class PrintWriterDemo { public static void main(String[] args) { PrintWriter pw = new PrintWriter(System.out,true); pw.println(“using print writer object”); int i=-7; pw.println(i); double d=4.5; pw.println(d); } }
  • 20. Scanner Class • To read from the keyboard, we create a Scanner as follows: Scanner sc=new Scanner(System.in); • To read from a file, create a Scanner for a file, as follows: Scanner sc=new Scanner(new File(filename)); Scanner Methods: next() nextLine() nextInt() ……
  • 21. 21
  • 22. Streams • Stream: an object that either delivers data to its destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.) • it acts as a buffer between the data source and destination • Input stream: a stream that provides input to a program • System.in is an input stream • Output stream: a stream that accepts output from a program • System.out is an output stream • A stream connects a program to an I/O object • System.out connects a program to the screen • System.in connects a program to the keyboard Input stream output stream
  • 23. Streams Types • Java defines two different types of Streams- ByteStream CharacterStream ByteStreams • Works with bytes and binary objects • InputStream class for read operation • OutputStream class for write operation CharacterStreams • Works with characters and strings • Reader class for read operation • Writer for write operation
  • 24. Text File I/O • Important classes for text file output (to the file) • PrintWriter • FileOutputStream [or FileWriter] • Important classes for text file input (from the file): • BufferedReader • FileReader • FileOutputStream and FileReader take file names as arguments. • PrintWriter and BufferedReader provide useful methods for easier writing and reading. • Usually need a combination of two classes • To use these classes your program needs a line like the following: import java.io.*;
  • 25. Byte Streams • Programs use byte streams to perform input and output of 8-bit bytes • Byte streams are defined by using two class hierarchies • At the top, there are two abstract classes : InputStream and OutputStream • The abstract classes InputStream and OutputStream define several key methods that the other stream classes implement • Two of the most important methods are read() and write() , which respectively read and write bytes of data • Both methods are declared as abstract inside InputStream and OutputStream • It is important that we have used a finally block to guarantee that both streams will be closed even if an error occurs. This helps resource leaks. • When we call the close() , it clears buffer by performing the write operation to the destination and then closes the stream.
  • 26. Byte Stream classes The following are the child classes for InputStream and OutputStream
  • 27. Byte Stream : InputStream and OutputStream classes The following are the child classes for InputStream and OutputStream. BufferedInputStream : contain methods to read from input stream buffer BufferOutputStream : to write DataInputStream : contain methods for reading the Java standard data types DataOutputStream : contain methods for writing the Java standard data types FileInputStream : Input stream that reads from a file FileOutputStream : output stream the writes to a file InputStream : abstract class that describes stream inputs OutputStream : abstract class that describes stream outputs PrintStream : output stream that contains print() and println() PipedInputStream : Input pipe PipedOutputStream : Output pipe
  • 28. Byte Stream : InputStream Methods The following are the methods for InputStream. int available() void close() void mark(int numbytes) int read() int read(byte buffer[]) void reset()
  • 29. Byte Stream : OutputStream Methods The following are the methods for OutputStream. void close() void flush() void write(int b) void write(byte[] buffer) void write(byte[] buffer, int offset, int numBytes)
  • 30. Byte Stream : File operation • FileInputStream and FileOutputStream are stream classes which create streams linked to files. • Constructor • FileInputStream(String filename) throws FileNotFoundException • FileInputStream(File fname) throws FileNotFoundException • FileOutputStream(String filename) throws FileNotFoundException • FileOutputStream(File fname) throws FileNotFoundException • FileOutputStream(String filename, boolean append) throws FileNotFoundException • FileOutputStream(File fname, boolean) throws FileNotFoundException
  • 31. Byte Stream : File operation • To read from a file , we can use read() that is defined within FileInputStream • int read() throws IOException • Each time read() is called, it reads a single byte from the file and returns the byte as an integer value. • To write a file, we can use the write() method defined by FileOutputStream. • void write(int bytevalue) throws IOException
  • 32. Byte Stream : copying a file , send source and target names using command line argument import java.io.*; public class Test { public static void main(String[] args) throws IOException { int i; FileInputStream fin=null; FileOutputStream fout=null; fin = new FileInputStream(args[0]); fout=new FileOutputStream(args[1]); try { while((i=fin.read())!=-1) { fout.write(i); } }catch(Exception e) { System.out.println(“File error”); } System.out.println(“one File copied”); fin.close(); fout.close(); }}
  • 33. Character Streams • Programs use character streams to perform input and output of 16-bit Unicodes that java supports. • Character streams are defined by using two class hierarchies • At the top, there are two abstract classes : Reader and Writer • The abstract classes Reader and Writer define several key methods that the other character classes implement
  • 34. Character Streams : Reader Class • The abstract classes Reader define several key methods that the other character classes implement. • The subclasses those implements the method of Reader are 1. BufferedReader : read characters from buffer 2. CharArrayReader : read characters from character array 3. FileReader : read characters from the file 4. FilterReader : read characters from the character input stream 5. InputStreamReader : converts bytes to character 6. PipedReader : read characters from a piped output stream 7. StringReader : read characters from a string
  • 35. Character Streams : Reader Methods • The abstract classes Reader define several key methods that the other character classes implement. • Methods declared abstract in Reader classes are : • int read() • int read(char[] buffer) • int read(char[] buffer, int loc, int nchars) • void reset() • void close()
  • 36. Character Streams : Writer Class • The abstract classes Writer define several key methods that the other character classes implement. • The subclasses those implements the method of Writer are 1. BufferedWriter : write characters to buffer 2. FileWriter : write characters to file 3. CharArrayWriter : write characters to the character array 4. OutputStreamWriter : converts bytes to character 5. PipedWriter : write characters to a piped output stream 6. StringWriter : write characters to a string
  • 37. Character Streams : Writer Methods • The abstract classes Writer define several key methods that the other character classes implement. • Methods declared abstract in Writer classes are : • void write() • void write(int i) • void write(char[] buffer, int loc, int nchars) • void flush() • void close()
  • 38. 38
  • 39. NIO api : introduces channel and Buffer Drawbacks of traditional java.io.* • Lacks some important functionality , such as copy() not available in File class • Defined many methods that returns boolean. In case of error , instead of exception, method returns false. • A limited set of file attributes was provided. Features of java.nio.* • Added with java 6/ jdk 6 • Stands for non blocking i/o • Bulk access to raw bytes • Bidirectional channels • Introduces three new concepts : Channel, Buffer and Selector
  • 40. Channel • The channel is where the data comes from. • The channel object is an object that connect to a file . • A channel can write the buffer to the medium or can read data from that medium to a buffer. • In Java , Channel is an interface • Implemented by FileChannel, DatagramChannel, SocketChannel
  • 41. Channel : FileChannel • A FileChannel can be mapped to a memory array for direct access. This allows for much faster operation than accessing to the disk directly. • It is built on native features provided by the different operating system and this is the reason why the concrete implementation of FileChannel are hidden just bcz they are different depending on the machine we are working on. • There are 3 modes of operation by a channel • READ_ONLY • READ_WRITE • PRIVATE
  • 42. Buffer • A buffer can be seen as a space in memory. It can reside in the main memory of the JVM. • A buffer object has 3 properties: • a capacity = the size of the backing array. • a current position that can be seen as cursor. All the read and the write operations are made to or from the current position. • a limit which is the last position in memory seen by this buffer. • A buffer supports 4 operations: • rewind: clears the mark and sets the current position to 0. • reset: sets the current position to the previously set mark. This is the companion method of the mark method. • flip: sets the limit to the current position and rewinds the buffer. • clear: clears the buffer.
  • 43. Buffer • Buffer is an abstract class in java. • Extended by ByteBuffer, CharBuffer,
  • 44. Exercise : Writing content to a file using Buffers and Channels • Steps: • Create a ByteBuffer. • use the putXXX() method to write data. • have our FileChannel to write the ByteBuffer to a file.
  • 45. 45
  • 52. Observer and Observable Interface The Java language supports the MVC architecture with two classes: Observer : Any object that wishes to be notified when the state of another object changes Observable : Any object whose state may be of interest, and in whom another object may register an interest. 52
  • 53. 53 Module – 2 Completed