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
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
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
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.");
}
}
}
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
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