SlideShare una empresa de Scribd logo
1 de 42
www.SunilOS.com 1
Java IO Steams
www.SunilOS.com | www.RaysTec.com
01110001001100
01110001001100
Input stream
Output stream
Reading and Writing
www.sunilos.com 2
Leaf
Stone
Paper Computer
Data - 01110001001100
www.sunilos.com 3
•Image files
•Video files
•Audio files
•Doc files
•Other files
Binary Data
Text Data
•.txt
•.java
•.bat
110001001100
01110001001100
This is Ram
This is Ram
byte byte
char
1 byte = 8 bit
Text Data
www.sunilos.com 4
Sources and Targets
www.sunilos.com 5
Network
File
Hardware
IO package
Package java.io contains classes to read
and write the data.
Binary data is read by InputStream and
write by OutputStream classes and
their child classes
Text data is read by Reader and write by
Writer classes and their child classes
www.sunilos.com 6
InputStream and OutputStream hierarchy
www.sunilos.com 7
Reader and Writer hierarchy
www.sunilos.com 8
Read data from a Text File
www.sunilos.com 9
ABCD1234567890
Read text file - FileReader
1. import java.io.FileReader;
2. public class ReadTextFile {
3. public static void main(String[] args) throws IOException {
4. FileReader in = new FileReader("f:/test.txt");
5. int ch = in.read(); // reads a character
6. while (ch != -1) { // -1 is end of file
7. System.out.print( (char) ch );
8. ch = in.read();
9. }
10. in.close();
11. }
12.}
www.sunilos.com 10
www.sunilos.com 11
Read a character
1010
Text Data
•.txt
•.java
•.bat
ABCD
FileReader
Char
Byte
www.sunilos.com 12
ASCII Table
try-with-resources
1. public static void main(String[] args) throws IOException {
2. try (FileReader in = new FileReader("f:/test.txt")) {
3. int ch = in.read();
4. while (ch != -1) { // -1 is end of file
5. System.out.print((char) ch);
6. ch = in.read();
7. }
8. }//try block end
9. }
www.sunilos.com 13
www.sunilos.com 14
Read a file line by line
 public static void main(String[] args) throws IOException {
1. FileReader file= new FileReader("c:/test.txt");
2. BufferedReader in= new BufferedReader(file);
3. String line = in.readLine();
4. while (line != null) {
5. System.out.println(line);
6. line = in.readLine();
7. }
8. in.close();
 }
• New line character n
www.sunilos.com 15
Read file: line by line
1010
Text Data
•.txt
•.java
•.bat
ABCD This is Line
BufferedReader
FileReader
Char Line
Byte
Byte
Char
Line
www.sunilos.com 16
Read File By Scanner
 java.util.Scanner class is used to parse primitive data and
strings from a text stream. It does not throw checked
exceptions.
public static void main(String[] args) throws Exception{
FileReader reader = new FileReader("c:/newtest.txt");
Scanner sc = new Scanner(reader);
while(sc.hasNext()){
System.out.println(sc.nextLine());
}
reader.close();
}
www.sunilos.com 17
Write to a File
public static void main(String[] args) throws IOException {
FileWriter out = new FileWriter("f:/newtest.txt");
out.write('A');
out.write('n'); //new line character
out.write("This is line one");
out.write("This is line two");
out.close();
System.out.println("Check f:/newtest.txt");
}
FileWriter will always create a new file.
Old file will be overwritten
www.sunilos.com 18
Write data line by line : PrintWriter
public static void main(String[] args) throws IOException {
FileWriter out = new FileWriter(“f:/newtest.txt");
PrintWriter pw= new PrintWriter( out);
for (int i = 0; i < 5; i++) {
pw.println(i + " : Line");
}
pw.close();
out.close();
System.out.println("Check c:/newtest.txt ");
}
www.sunilos.com 19
Write to a File
1010
ABCD
•Text Data
•.txt
•.java
•.bat
This is Line
PrintWriter
FileWriter
Char
Line
Byte
Contains print and println methods
Line
Char
Byte
Copy a binary file
1. String source= "c:/baby1.jpg";
2. String target = "c:/baby2.jpg";
3. FileInputStream in= new FileInputStream(source);
4. FileOutputStream out= new FileOutputStream(target);
5. int ch = in.read() ;
6. while (ch != -1){
1. out.write(ch);
2. ch = in.read();
7. }
8. in.close();
9. out.close();
10. System.out.println(source + " is copied to "+ target);
www.sunilos.com 20
Append data to the File
www.sunilos.com 21
www.sunilos.com 22
Append Text/Bytes in existing File
FileWriter/ FileOutputStream will always create a
new file. Old data is overwritten.
If you append new data in old file then pass second
parameter Boolean value ‘true’ to the constructor:
o new FileWriter(“c:a.txt”,true)
o new FileOutputStream (“c:a.jpg”,true)
Exception Handling
 Java throws IOException in case of abnormal condition during
o Opening file
o Reading file
o Writing file
o Closing the file
Exception can be handled by try-catch block
We have propagated exception from main method
o public static void main(String[] args) throws IOException
www.sunilos.com 23
Read from Keyboard
www.sunilos.com 24
Convert Binary to Text Stream
Class : InputStreamReader
Reads Data From Keyboard
o InputStreamReader ir= new InputStreamReader(System.in);
www.sunilos.com 25
1010
ABCD
Char
Byte
InputStreamReader
www.sunilos.com 26
Read from Keyboard (Hardware)
1. Reads data from keyboard and writes into a file
2. InputStreamReader isReader = new InputStreamReader(System.in);
3. BufferedReader in = new BufferedReader(isReader );
4. PrintWriter out = new PrintWriter(new FileWriter("c:/temp.txt"););
5. String line = in.readLine();
6. while (!line.equals("quit")) {
7. out.println(line);
8. line = in.readLine();
9. }
10. out.close();
11. in.close();
www.sunilos.com 27
Read file attributes
import java.io.File; java.util.Date;
public static void main(String[] args) {
File f = new File("c:/temp/a.txt”");
if(f.exists()){
System.out.println(“Name” + f.getName());
System.out.println(“Absolute path: “ + f.getAbsolutePath());
System.out.println(" Is writable: “ + f.canWrite());
System.out.println(" Is readable: “ + f.canRead());
System.out.println(" Is File“ + f.isFile());
System.out.println(" Is Directory“ + f.isDirectory());
System.out.println("Last Modified at " + new Date(f.lastModified()));
System.out.println(“Size " + f.length() + " bytes long.");
}
}
}
www.SunilOS.com 28
Java Serialization
www.SunilOS.com | www.RaysTec.com
01110001001100
01110001001100
Serialization
Deserialization
Object
Serialization / Deserialization
www.sunilos.com 29
Serialization
Deserialization
Serialization / Deserialization
www.sunilos.com 30
Serialization
Deserialization
Object
1010101010101000001111
Convert to byte stream
Convert to object
Everything is an Object
www.sunilos.com 31
Employee
RAM
Sharma
Manager
10 Lac
India
10001
10011
10010
10101
10111
Contiguous bytes to store => 1010101010101000001111
When?
When an object go out of JVM
www.sunilos.com 33
Network
File
JVM Data Out
Which classes?
 Class implements java.io.Serializable interface
 Serializable interface contains Zero methods, it is a marker
interface.
www.sunilos.com 34
Employee
Serializable
Marksheet
Serializable
Class
Serializable
How?
Java provides two classes to serialize and deserialize
an object:
o ObjectOutputStream: for serialization
o ObjectInputStream: for deserialization
www.sunilos.com 35
Marksheet
1. import java.io.Serializable;
2. public class Marksheet implements Serializable {
3. public String name = null;
4. public int maths = 0;
5. public int physics = 0;
6. public int chemistry = 0;
7. }
www.sunilos.com 36
WriteObject
1. public class WriteObject {
2. public static void main(String[] args) throws IOException {
3. FileOutputStream file = new FileOutputStream("f:/object.ser");
4. ObjectOutputStream out = new ObjectOutputStream(file);
5. Marksheet m = new Marksheet();
6. m.name = "Ram";
7. m.physics = 89;
8. m.chemistry = 99;
9. m.maths = 95;
10. out.writeObject(m);
11. out.close();
12. file.close();
13. }
14. }
www.sunilos.com 37
ReadObject
1. public class ReadObject {
2. public static void main(String[] args) throws Exception {
3. FileInputStream file = new FileInputStream("f:/object.ser");
4. ObjectInputStream in = new ObjectInputStream(file);
5. Marksheet m = (Marksheet) in.readObject();
6. System.out.println(m.name);
7. System.out.println(m.physics);
8. System.out.println(m.chemistry);
9. System.out.println(m.maths);
10. in.close();
11. file.close();
12. }
13. }
www.sunilos.com 38
Transient Attributes
1. import java.io.Serializable;
2. public class Marksheet implements Serializable {
3. public String name = null;
4. public int maths = 0;
5. public int physics = 0;
6. public int chemistry = 0;
7. private transient int total = 0;
8. private transient double percentage = 0;
9. }
10. Transient variables will be discarded during serialization
www.sunilos.com 39
Externalizable interface
1. Developers can use Externalizable
interface to write custom code to serialize and
deserialize an object.
2. Externalizable interface has two methods
1.readExternal() to read the object
2.writeExternal() to write the object
www.sunilos.com 40
Employee implements Externalizable
1. public class Employeeimplements Externalizable{
2. public String id = null;
3. public String firstName = null;
4. public String lastName = null;
5. public double salary = 0;
6. @Override
7. public void readExternal(ObjectInput in) throws Exception {
8. id = (String) in.readObject();
9. firstName = (String) in.readObject();
10. lastName = (String) in.readObject();
11. salary = in.readDouble();
12. }
13. @Override
14. public void writeExternal(ObjectOutput out) throws Exception {
15. out.writeObject(id);
16. out.writeObject(firstName);
17. out.writeObject(lastName);
18. out.writeDouble(salary);
19. }
www.sunilos.com 41
What we have learned?
 IO Streams
 Read and write text file
 Read and write binary file
 try-with-resources block
 Read from keyboard
 Read file attributes
 Serialization
 Deserialization
 Externalizable interface
www.SunilOS.com 42
Thank You!
www.SunilOS.com 43
www.SunilOS.com

Más contenido relacionado

La actualidad más candente

JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and OperatorsSunil OS
 
Exception Handling
Exception HandlingException Handling
Exception HandlingSunil OS
 
Hibernate
Hibernate Hibernate
Hibernate Sunil OS
 
Resource Bundle
Resource BundleResource Bundle
Resource BundleSunil OS
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and ConcurrencySunil OS
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File HandlingSunil OS
 
Java Basics
Java BasicsJava Basics
Java BasicsSunil OS
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/ServletSunil OS
 
Machine learning ( Part 1 )
Machine learning ( Part 1 )Machine learning ( Part 1 )
Machine learning ( Part 1 )Sunil OS
 
Python part2 v1
Python part2 v1Python part2 v1
Python part2 v1Sunil OS
 
Python Part 1
Python Part 1Python Part 1
Python Part 1Sunil OS
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8Knoldus Inc.
 
Machine learning ( Part 3 )
Machine learning ( Part 3 )Machine learning ( Part 3 )
Machine learning ( Part 3 )Sunil OS
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classesIntro C# Book
 

La actualidad más candente (20)

JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Hibernate
Hibernate Hibernate
Hibernate
 
Resource Bundle
Resource BundleResource Bundle
Resource Bundle
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Log4 J
Log4 JLog4 J
Log4 J
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Java Basics
Java BasicsJava Basics
Java Basics
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
C++
C++C++
C++
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Machine learning ( Part 1 )
Machine learning ( Part 1 )Machine learning ( Part 1 )
Machine learning ( Part 1 )
 
PDBC
PDBCPDBC
PDBC
 
DJango
DJangoDJango
DJango
 
Python part2 v1
Python part2 v1Python part2 v1
Python part2 v1
 
Python Part 1
Python Part 1Python Part 1
Python Part 1
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
 
Machine learning ( Part 3 )
Machine learning ( Part 3 )Machine learning ( Part 3 )
Machine learning ( Part 3 )
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 

Similar a Java IO Streams V4

File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptxcherryreddygannu
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streamsShahjahan Samoon
 
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OCore Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OWebStackAcademy
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdfSudhanshiBakre1
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and OutputEduardo Bergavera
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12Vince Vo
 
Input output files in java
Input output files in javaInput output files in java
Input output files in javaKavitha713564
 
What is java input and output stream?
What is java input and output stream?What is java input and output stream?
What is java input and output stream?kanchanmahajan23
 
What is java input and output stream?
What is java input and output stream?What is java input and output stream?
What is java input and output stream?kanchanmahajan23
 
ch06-file-processing.ppt
ch06-file-processing.pptch06-file-processing.ppt
ch06-file-processing.pptMahyuddin8
 
Hi, I need help with a java programming project. specifically practi.pdf
Hi, I need help with a java programming project. specifically practi.pdfHi, I need help with a java programming project. specifically practi.pdf
Hi, I need help with a java programming project. specifically practi.pdfPRATIKSINHA7304
 
Secure erasure code based cloud storage system with secure data forwarding
Secure erasure code based cloud storage system with secure data forwardingSecure erasure code based cloud storage system with secure data forwarding
Secure erasure code based cloud storage system with secure data forwardingPriyank Rupera
 

Similar a Java IO Streams V4 (20)

ExtraFileIO.pptx
ExtraFileIO.pptxExtraFileIO.pptx
ExtraFileIO.pptx
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OCore Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
 
CORE JAVA-1
CORE JAVA-1CORE JAVA-1
CORE JAVA-1
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12
 
15. text files
15. text files15. text files
15. text files
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
Lab4
Lab4Lab4
Lab4
 
Java 3 Computer Science.pptx
Java 3 Computer Science.pptxJava 3 Computer Science.pptx
Java 3 Computer Science.pptx
 
IO and threads Java
IO and threads JavaIO and threads Java
IO and threads Java
 
File Handling.pptx
File Handling.pptxFile Handling.pptx
File Handling.pptx
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
What is java input and output stream?
What is java input and output stream?What is java input and output stream?
What is java input and output stream?
 
What is java input and output stream?
What is java input and output stream?What is java input and output stream?
What is java input and output stream?
 
ch06-file-processing.ppt
ch06-file-processing.pptch06-file-processing.ppt
ch06-file-processing.ppt
 
Hi, I need help with a java programming project. specifically practi.pdf
Hi, I need help with a java programming project. specifically practi.pdfHi, I need help with a java programming project. specifically practi.pdf
Hi, I need help with a java programming project. specifically practi.pdf
 
Secure erasure code based cloud storage system with secure data forwarding
Secure erasure code based cloud storage system with secure data forwardingSecure erasure code based cloud storage system with secure data forwarding
Secure erasure code based cloud storage system with secure data forwarding
 

Más de Sunil OS

Threads v3
Threads v3Threads v3
Threads v3Sunil OS
 
Exception Handling v3
Exception Handling v3Exception Handling v3
Exception Handling v3Sunil OS
 
Machine learning ( Part 2 )
Machine learning ( Part 2 )Machine learning ( Part 2 )
Machine learning ( Part 2 )Sunil OS
 
Python Pandas
Python PandasPython Pandas
Python PandasSunil OS
 
Angular 8
Angular 8 Angular 8
Angular 8 Sunil OS
 
C# Variables and Operators
C# Variables and OperatorsC# Variables and Operators
C# Variables and OperatorsSunil OS
 
Rays Technologies
Rays TechnologiesRays Technologies
Rays TechnologiesSunil OS
 
Java Swing JFC
Java Swing JFCJava Swing JFC
Java Swing JFCSunil OS
 

Más de Sunil OS (12)

OOP v3
OOP v3OOP v3
OOP v3
 
Threads v3
Threads v3Threads v3
Threads v3
 
Exception Handling v3
Exception Handling v3Exception Handling v3
Exception Handling v3
 
Machine learning ( Part 2 )
Machine learning ( Part 2 )Machine learning ( Part 2 )
Machine learning ( Part 2 )
 
Python Pandas
Python PandasPython Pandas
Python Pandas
 
Angular 8
Angular 8 Angular 8
Angular 8
 
C# Variables and Operators
C# Variables and OperatorsC# Variables and Operators
C# Variables and Operators
 
C# Basics
C# BasicsC# Basics
C# Basics
 
Rays Technologies
Rays TechnologiesRays Technologies
Rays Technologies
 
C++ oop
C++ oopC++ oop
C++ oop
 
C Basics
C BasicsC Basics
C Basics
 
Java Swing JFC
Java Swing JFCJava Swing JFC
Java Swing JFC
 

Último

Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxUmeshTimilsina1
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 

Último (20)

Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 

Java IO Streams V4

  • 1. www.SunilOS.com 1 Java IO Steams www.SunilOS.com | www.RaysTec.com 01110001001100 01110001001100 Input stream Output stream
  • 2. Reading and Writing www.sunilos.com 2 Leaf Stone Paper Computer
  • 3. Data - 01110001001100 www.sunilos.com 3 •Image files •Video files •Audio files •Doc files •Other files Binary Data Text Data •.txt •.java •.bat 110001001100 01110001001100 This is Ram This is Ram byte byte char 1 byte = 8 bit
  • 5. Sources and Targets www.sunilos.com 5 Network File Hardware
  • 6. IO package Package java.io contains classes to read and write the data. Binary data is read by InputStream and write by OutputStream classes and their child classes Text data is read by Reader and write by Writer classes and their child classes www.sunilos.com 6
  • 7. InputStream and OutputStream hierarchy www.sunilos.com 7
  • 8. Reader and Writer hierarchy www.sunilos.com 8
  • 9. Read data from a Text File www.sunilos.com 9 ABCD1234567890
  • 10. Read text file - FileReader 1. import java.io.FileReader; 2. public class ReadTextFile { 3. public static void main(String[] args) throws IOException { 4. FileReader in = new FileReader("f:/test.txt"); 5. int ch = in.read(); // reads a character 6. while (ch != -1) { // -1 is end of file 7. System.out.print( (char) ch ); 8. ch = in.read(); 9. } 10. in.close(); 11. } 12.} www.sunilos.com 10
  • 11. www.sunilos.com 11 Read a character 1010 Text Data •.txt •.java •.bat ABCD FileReader Char Byte
  • 13. try-with-resources 1. public static void main(String[] args) throws IOException { 2. try (FileReader in = new FileReader("f:/test.txt")) { 3. int ch = in.read(); 4. while (ch != -1) { // -1 is end of file 5. System.out.print((char) ch); 6. ch = in.read(); 7. } 8. }//try block end 9. } www.sunilos.com 13
  • 14. www.sunilos.com 14 Read a file line by line  public static void main(String[] args) throws IOException { 1. FileReader file= new FileReader("c:/test.txt"); 2. BufferedReader in= new BufferedReader(file); 3. String line = in.readLine(); 4. while (line != null) { 5. System.out.println(line); 6. line = in.readLine(); 7. } 8. in.close();  } • New line character n
  • 15. www.sunilos.com 15 Read file: line by line 1010 Text Data •.txt •.java •.bat ABCD This is Line BufferedReader FileReader Char Line Byte Byte Char Line
  • 16. www.sunilos.com 16 Read File By Scanner  java.util.Scanner class is used to parse primitive data and strings from a text stream. It does not throw checked exceptions. public static void main(String[] args) throws Exception{ FileReader reader = new FileReader("c:/newtest.txt"); Scanner sc = new Scanner(reader); while(sc.hasNext()){ System.out.println(sc.nextLine()); } reader.close(); }
  • 17. www.sunilos.com 17 Write to a File public static void main(String[] args) throws IOException { FileWriter out = new FileWriter("f:/newtest.txt"); out.write('A'); out.write('n'); //new line character out.write("This is line one"); out.write("This is line two"); out.close(); System.out.println("Check f:/newtest.txt"); } FileWriter will always create a new file. Old file will be overwritten
  • 18. www.sunilos.com 18 Write data line by line : PrintWriter public static void main(String[] args) throws IOException { FileWriter out = new FileWriter(“f:/newtest.txt"); PrintWriter pw= new PrintWriter( out); for (int i = 0; i < 5; i++) { pw.println(i + " : Line"); } pw.close(); out.close(); System.out.println("Check c:/newtest.txt "); }
  • 19. www.sunilos.com 19 Write to a File 1010 ABCD •Text Data •.txt •.java •.bat This is Line PrintWriter FileWriter Char Line Byte Contains print and println methods Line Char Byte
  • 20. Copy a binary file 1. String source= "c:/baby1.jpg"; 2. String target = "c:/baby2.jpg"; 3. FileInputStream in= new FileInputStream(source); 4. FileOutputStream out= new FileOutputStream(target); 5. int ch = in.read() ; 6. while (ch != -1){ 1. out.write(ch); 2. ch = in.read(); 7. } 8. in.close(); 9. out.close(); 10. System.out.println(source + " is copied to "+ target); www.sunilos.com 20
  • 21. Append data to the File www.sunilos.com 21
  • 22. www.sunilos.com 22 Append Text/Bytes in existing File FileWriter/ FileOutputStream will always create a new file. Old data is overwritten. If you append new data in old file then pass second parameter Boolean value ‘true’ to the constructor: o new FileWriter(“c:a.txt”,true) o new FileOutputStream (“c:a.jpg”,true)
  • 23. Exception Handling  Java throws IOException in case of abnormal condition during o Opening file o Reading file o Writing file o Closing the file Exception can be handled by try-catch block We have propagated exception from main method o public static void main(String[] args) throws IOException www.sunilos.com 23
  • 25. Convert Binary to Text Stream Class : InputStreamReader Reads Data From Keyboard o InputStreamReader ir= new InputStreamReader(System.in); www.sunilos.com 25 1010 ABCD Char Byte InputStreamReader
  • 26. www.sunilos.com 26 Read from Keyboard (Hardware) 1. Reads data from keyboard and writes into a file 2. InputStreamReader isReader = new InputStreamReader(System.in); 3. BufferedReader in = new BufferedReader(isReader ); 4. PrintWriter out = new PrintWriter(new FileWriter("c:/temp.txt");); 5. String line = in.readLine(); 6. while (!line.equals("quit")) { 7. out.println(line); 8. line = in.readLine(); 9. } 10. out.close(); 11. in.close();
  • 27. www.sunilos.com 27 Read file attributes import java.io.File; java.util.Date; public static void main(String[] args) { File f = new File("c:/temp/a.txt”"); if(f.exists()){ System.out.println(“Name” + f.getName()); System.out.println(“Absolute path: “ + f.getAbsolutePath()); System.out.println(" Is writable: “ + f.canWrite()); System.out.println(" Is readable: “ + f.canRead()); System.out.println(" Is File“ + f.isFile()); System.out.println(" Is Directory“ + f.isDirectory()); System.out.println("Last Modified at " + new Date(f.lastModified())); System.out.println(“Size " + f.length() + " bytes long."); } } }
  • 28. www.SunilOS.com 28 Java Serialization www.SunilOS.com | www.RaysTec.com 01110001001100 01110001001100 Serialization Deserialization Object
  • 29. Serialization / Deserialization www.sunilos.com 29 Serialization Deserialization
  • 30. Serialization / Deserialization www.sunilos.com 30 Serialization Deserialization Object 1010101010101000001111 Convert to byte stream Convert to object
  • 31. Everything is an Object www.sunilos.com 31 Employee RAM Sharma Manager 10 Lac India 10001 10011 10010 10101 10111 Contiguous bytes to store => 1010101010101000001111
  • 32. When? When an object go out of JVM www.sunilos.com 33 Network File JVM Data Out
  • 33. Which classes?  Class implements java.io.Serializable interface  Serializable interface contains Zero methods, it is a marker interface. www.sunilos.com 34 Employee Serializable Marksheet Serializable Class Serializable
  • 34. How? Java provides two classes to serialize and deserialize an object: o ObjectOutputStream: for serialization o ObjectInputStream: for deserialization www.sunilos.com 35
  • 35. Marksheet 1. import java.io.Serializable; 2. public class Marksheet implements Serializable { 3. public String name = null; 4. public int maths = 0; 5. public int physics = 0; 6. public int chemistry = 0; 7. } www.sunilos.com 36
  • 36. WriteObject 1. public class WriteObject { 2. public static void main(String[] args) throws IOException { 3. FileOutputStream file = new FileOutputStream("f:/object.ser"); 4. ObjectOutputStream out = new ObjectOutputStream(file); 5. Marksheet m = new Marksheet(); 6. m.name = "Ram"; 7. m.physics = 89; 8. m.chemistry = 99; 9. m.maths = 95; 10. out.writeObject(m); 11. out.close(); 12. file.close(); 13. } 14. } www.sunilos.com 37
  • 37. ReadObject 1. public class ReadObject { 2. public static void main(String[] args) throws Exception { 3. FileInputStream file = new FileInputStream("f:/object.ser"); 4. ObjectInputStream in = new ObjectInputStream(file); 5. Marksheet m = (Marksheet) in.readObject(); 6. System.out.println(m.name); 7. System.out.println(m.physics); 8. System.out.println(m.chemistry); 9. System.out.println(m.maths); 10. in.close(); 11. file.close(); 12. } 13. } www.sunilos.com 38
  • 38. Transient Attributes 1. import java.io.Serializable; 2. public class Marksheet implements Serializable { 3. public String name = null; 4. public int maths = 0; 5. public int physics = 0; 6. public int chemistry = 0; 7. private transient int total = 0; 8. private transient double percentage = 0; 9. } 10. Transient variables will be discarded during serialization www.sunilos.com 39
  • 39. Externalizable interface 1. Developers can use Externalizable interface to write custom code to serialize and deserialize an object. 2. Externalizable interface has two methods 1.readExternal() to read the object 2.writeExternal() to write the object www.sunilos.com 40
  • 40. Employee implements Externalizable 1. public class Employeeimplements Externalizable{ 2. public String id = null; 3. public String firstName = null; 4. public String lastName = null; 5. public double salary = 0; 6. @Override 7. public void readExternal(ObjectInput in) throws Exception { 8. id = (String) in.readObject(); 9. firstName = (String) in.readObject(); 10. lastName = (String) in.readObject(); 11. salary = in.readDouble(); 12. } 13. @Override 14. public void writeExternal(ObjectOutput out) throws Exception { 15. out.writeObject(id); 16. out.writeObject(firstName); 17. out.writeObject(lastName); 18. out.writeDouble(salary); 19. } www.sunilos.com 41
  • 41. What we have learned?  IO Streams  Read and write text file  Read and write binary file  try-with-resources block  Read from keyboard  Read file attributes  Serialization  Deserialization  Externalizable interface www.SunilOS.com 42

Notas del editor

  1. www.sunilos.com
  2. Helpline- 98273 60504
  3. Helpline- 98273 60504
  4. Helpline- 98273 60504
  5. Helpline- 98273 60504
  6. Helpline- 98273 60504
  7. Helpline- 98273 60504
  8. Helpline- 98273 60504
  9. Helpline- 98273 60504
  10. Helpline- 98273 60504
  11. Helpline- 98273 60504
  12. Helpline- 98273 60504
  13. Helpline- 98273 60504
  14. www.sunilos.com