SlideShare a Scribd company logo
Input/Output Streams
www.sunilos.com
www.raystec.com
www.sunilos.com 2
Input/Output Concepts
 Data Storage
o Transient memory : RAM
• It is accessed directly by processor.
o Persistent Memory: Disk and Tape
• It requires I/O operations.
 I/O sources and destinations
o console, disk, tape, network, etc.
 Streams
o It represents a sequential stream of bytes.
o It hides the details of I/O devices.
www.sunilos.com 3
IO Stream– java.io package
101010 101010Byte Array Byte Array
1010 1010ABCD
Binary Data
•.exe
•.jpg
•.class
Text Data
•.txt
•.java
•.bat
ABCDThis is Line This is Line
InputStream
ByteByte
OutputStream
BufferedOutputStream
BufferedInputStream
BufferedWriter
BufferedReader
Writer Reader
Char
Line
Char Line
Byte
Byte
• FileWriter
• PrintWriter
• FileReader
• InputStreamReader
• Scanner
• FileOutputStream
• ObjectOutputStream
• FileInputStream
• ObjectInputStream
www.sunilos.com 4
Types Of Data
 character data
o Represented as 1-byte ASCII .
o Represented as 2-bytes Unicode within Java programs. The
first 128 characters of Unicode are the ASCII characters.
o Read by Reader and its subclasses.
o Written by Writer and its subclasses.
o You can use java.util.Scanner to read characters in
JDK1.5 onward.
 binary data
o Read by InputStream and its subclasses.
o Written by OutputStream and its subclasses.
www.sunilos.com 5
Attrib.java : c:>java Attrib <fileName>
import java.io.File; java.util.Date;
public static void main(String[] args) {
File f = new File("c:/temp/a.txt”");
// 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(“Length " + f.length() + " bytes long.");
}
}
}
www.sunilos.com 6
Representing a File
 Class java.io.File represents a file or folder (directory).
o Constructors:
• public File (String path)
• public File (String path, String name)
o Interesting methods:
• boolean exists()
• boolean isDirectory()
• boolean isFile()
• boolean canRead()
• boolean canWrite()
• long length()
• long lastModified()
www.sunilos.com 7
Representing a File (Cont.)
More interesting methods:
o boolean delete()
o boolean renameTo(File dest)
o boolean mkdir()
o String[] list()
o File[] listFiles()
o String getName()
www.sunilos.com 8
Display file and subdirectories
This program displays files and subdirectories of
a directory.
public static void main(String[] args) {
File directory = new File("C:/temp");
//File directory = new File(args[0]);
String[] list = directory.list();
for (int i = 0; i < list.length; i++) {
System.out.println((i + 1) + " : " +
list[i]);
}
}
www.sunilos.com 9
Display only files from a folder
public static void main(String[] args) {
File directory = new File("C:/temp");
//File directory = new File(args[0]);
String[] list = directory.list();
for (int i = 0; i < list.length; i++) {
File f = new File(“c:/temp”,list[i]);
if(f.isFile()){
System.out.println((i + 1) + " : " + list[i]);
}
}
}
www.sunilos.com 10
Display only files from a folder
public static void main(String[] args) {
File directory = new File("C:/temp");
File[] list = directory.listFiles();
for (int i = 0; i < list.length; i++) {
if (list[i].isFile()) {
System.out.println((i + 1) + " : " + list[i].getName());
}
}
}
www.sunilos.com 11
FileReader- Read char from a file
public static void main(String[] args) throws Exception{
FileReader reader = new FileReader(“c:/test.txt”);
int ch = reader.read();
char chr;
while(ch != -1){
chr = (char)ch;
System.out.print( chr);
ch = reader.read();
}
}
www.sunilos.com 12
Read a file line by line
public static void main(String[] args) throws Exception {
FileReader reader = new FileReader("c:/test.txt");
BufferedReader br= new BufferedReader(reader);
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
reader.close();
}
www.sunilos.com 13
Read file by Line
1010
Text Data
•.txt
•.java
•.bat
ABCD This is Line
BufferedReader
FileReader
Char LineByte
Byte
Char
Line
www.sunilos.com 14
Write to a File
public static void main(String[] args) throws Exception {
FileWriter writer = new FileWriter("c:/newtest.txt");
PrintWriter pw= new PrintWriter(writer);
for (int i = 0; i < 5; i++) {
pw.println(i + " : Line");
}
pw.close();
writer.close();
System.out.println(“File is successfully written, Pl check c:/newtest.txt ");
}
www.sunilos.com 15
Write to a File
1010ABCD
•Text Data
•.txt
•.java
•.bat
This is Line
PrintWriter
FileWriter
Char
Line
Byte
Contains print and println methods
Line
Char
Byte
www.sunilos.com 16
Append Text/Bytes in existing File
 FileWriter: You may use either constructor to create a
FileWriter object to append text in an existing file.
o FileWriter(“c:a.txt”,true)
o FileWriter(new File(“c:a.txt”),true)
 FileOutputStream: You may use either constructor to create a
FileOutputStream object to append bytes in an existing binary
file.
o FileOutputStream (“c:a.jpg”,true)
o FileOutputStream (new File(“c:a.jpg”),true)
Copy A Text File
 String source= "c:/a.txt";
 String target = "c:/b.txt";
 FileReader reader = new FileReader(source);
 FileWriter writer = new FileWriter(target);
 int ch = reader.read() ;
 while (ch != -1){
o writer.write(ch);
o ch = reader.read();
 }
 writer.close();
 reader.close();
 System.out.println(source + " is copied to "+ target);
www.sunilos.com 17
Copy A Binary File
 String source= "c:/IMG_0046.JPG";
 String target = "c:/baby.jpg";
 FileInputStream reader = new FileInputStream(source);
 FileOutputStream writer = new FileOutputStream(target);
 int ch = reader.read() ;
 while (ch != -1){
o writer.write(ch);
o ch = reader.read();
 }
 writer.close();
 reader.close();
 System.out.println(source + " is copied to "+ target);
www.sunilos.com 18
Convert Binary to Text Stream
Class : InputStreamReader
Reads Data From Keyboard
o InputStreamReader ir= new InputStreamReader(System.in);
www.sunilos.com 19
1010
ABCD
CharByte
InputStreamReader
www.sunilos.com 20
Copycon command
 Reads data from keyboard and writes into a file
 String target= "c:/temp.txt";
 FileWriter writer = new FileWriter(target);
 PrintWriter printWriter = new PrintWriter(writer);
 InputStreamReader isReader = new InputStreamReader(System.in);
 BufferedReader in = new BufferedReader(isReader );
 String line = in.readLine();
 while (!line.equals("quit")) {
o printWriter.print(line);
o line = in.readLine();
 }
 printWriter.close();
 isReader.close();
www.sunilos.com 21
Serialization
 public class Employee implements Serializable {
 private int id;
 private String firstName;
 private String lastName;
 private Address add;
 private transient String tempValue;
 public Employee() { //Default Constructor }
 public Employee(int id, String firstName, String lastName) {
o this.id = id;
o this.firstName = firstName;
o this.lastName = lastName;
 }
 //accessor methods
Serialization
www.sunilos.com 22
Why Serialization ?
When an object is persisted in a file.
When an object is sent over the Network.
When an object is sent to Hardware.
Or in other words when an object is sent Out of
JVM.
www.sunilos.com 23
Persist/Write an Object
 FileOutputStream file = new
FileOutputStream("c:/object.ser");
 ObjectOutputStream out = new ObjectOutputStream(file);
 Employee emp = new Employee(10, “Sachin", “10lukar");
 out.writeObject(emp);
 out.close();
 System.out.println("Object is successfully persisted");
www.sunilos.com 24
Read an Object
www.sunilos.com 25
 FileInputStream file= new FileInputStream("c:/object.ser")
 ObjectInputStream in = new ObjectInputStream(file);
 Employee emp = (Employee) in.readObject();
 System.out.println("ID : " + emp.getId());
 System.out.println("F Name : " + emp.getFirstName());
 System.out.println("L Name : " + emp.getLastName());
 System.out.println("Temp Value: " + emp.getTempValue());
 NOTE : transient variables will be discarded during serialization
www.sunilos.com 26
Write Primitive Data
What are primitive data types?
o int
o double
o float
o boolean
o char
Which classes to use?
o DataInputStream
o DataOutputStream
Write Primitive Data
 public static void main(String[] args) throws Exception {
o FileOutputStream file = new
FileOutputStream("c:/primitivedata.dat");
o DataOutputStream out = new DataOutputStream(file);
o out.writeInt(1);
o out.writeBoolean(true);
o out.writeChar('A');
o out.writeDouble(1.2);
o out.close();
o file.close()
o System.out.println("Primitive Data successfully written");
 }
www.sunilos.com 27
Read Primitive Data
 public static void main(String[] args) throws Exception {
o FileInputStream file = new
FileInputStream("c:/primitivedata.dat");
o DataInputStream in = new DataInputStream(file);
o System.out.println(in.readInt());
o System.out.println(in.readBoolean());
o System.out.println(in.readChar());
o System.out.println(in.readDouble());
o in.close();
 }
www.sunilos.com 28
www.sunilos.com 29
Primitive File - Write
public static void main(String[] args) throws Exception {
long dataPosition = 0; // to be determined later
RandomAccessFile in = new RandomAccessFile("datafile.dat", "rw");
// Write to the file.
in.writeLong(0); // placeholder
in.writeChars("blahblahblah");
dataPosition = in.getFilePointer();
in.writeInt(123);
in.writeBytes(“Blahblahblah");
// Rewrite the first byte to reflect updated data position.
in.seek(0);
in.writeLong(dataPosition);
in.close();
}
www.sunilos.com 30
Primitive File - Read
public static void main(String[] args) throws Exception {
long dataPosition = 0;
int data = 0;
RandomAccessFile raf = new RandomAccessFile("datafile", "r");
// Get the position of the data to read.
dataPosition = raf.readLong();
System.out.println("dataPosition : " + dataPosition);
// Go to that position.
raf.seek(dataPosition);
// Read the data.
data = raf.readInt();
raf.close();
System.out.println("The data is: " + data);
}
www.sunilos.com 31
java.util.Scanner
 A simple text scanner which can parse primitive data
types and strings using regular expressions.
 Reads character data as Strings, or converts to primitive
values.
 Does not throw checked exceptions.
 Constructors
o Scanner (File source) // reads from a file
o Scanner (InputStream source) // reads from a stream
o Scanner (String source) // scans a String
www.sunilos.com 32
java.util.Scanner
Interesting methods:
o boolean hasNext()
o boolean hasNextInt()
o boolean hasNextDouble()
o …
o String next()
o String nextLine()
o int nextInt()
o double nextDouble()
www.sunilos.com 33
Read File By Scanner
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();
}
Token A String
Breaks string into tokens.
 public static void main(String[] args) {
o String str = “This is Java, Java is Object Oriented
Language, Java is guarantee for job";
o StringTokenizer stn = new StringTokenizer(str, ",");
o String token = null;
o while (stn.hasMoreElements()) {
o token = stn.nextToken();
o System.out.println(“Token is : " + token);
o }
 }
www.sunilos.com 34
www.sunilos.com 35
Summary
 What is IO Package
o java.io
 How to represent a File/Directory
o File f = new File(“c:/temp/myfile.txt”)
• OR
o File f = new File(“c:/temp”,”myfile.txt”)
www.sunilos.com 36
Summary (Cont.)
How to write text data char by char?
o FileWriter out = new FileWrite(f);
• OR
o FileWriter out = new FileWrite (“c:/temp/myfile.txt”);
o out.write(‘A’);
How to write text data line by line?
o PrintWriter pOut = new PrintWriter(out);
o pOut.println(“This is Line”);
www.sunilos.com 37
Summary (Cont.)
How to read text data char by char?
o FileReader in = new FileReader(f);
• OR
o FileReader in = new FileReader (“c:/temp/myfile.txt”);
o in.read();
How to read text data line by line?
o BufferedReader pIn= new BufferedReader(in);
o pIn.readLine();
o Scanner.readLine()
www.sunilos.com 38
Summary (Cont.)
How to write binary data byte by byte?
o FileOutputStream out = new FileOutputStream(f);
• OR
o FileOutputStream out = new FileOutputStream
(“c:/temp/myfile.txt”);
o out.write(1);
How to write binary data as byte array?
o BufferedOutputStream bOut = new BufferedOutputStream
(out);
o bOut.write(byte[]);
www.sunilos.com 39
Summary (Cont.)
 How to read binary data byte by byte?
o FileInputStream in = new FileInputStream(f);
• OR
o FileInputStream in = new FileInputStream
(“c:/temp/myfile.txt”);
o in.read();
 How to read binary data as byte array?
o BufferedInputStream bIn = new BufferedInputStream (in);
o byte[] buffer = new byte[256];
o bIn.read(buffer);
www.sunilos.com 40
Summary (Cont.)
How to write primitive data?
o FileOutputStream file = new
FileOutputStream("c:/primitivedata.dat");
o DataOutputStream out = new DataOutputStream(file);
How to Read primitive data?
o FileInputStream file = new
FileInputStream("c:/primitivedata.dat");
o DataInputStream in = new DataInputStream(file);
www.sunilos.com 41
Summary (Cont.)
 How to persist/write an Object
o Make object Serialized
o FileOutputStream file = new FileOutputStream("c:/object.ser");
o ObjectOutputStream out = new ObjectOutputStream(file);
o out.writeObject(obj);
 How to read an Object
o FileInputStream file = new FileInputStream("c:/object.ser");
o ObjectInputStream in = new ObjectInputStream(file);
o Object obj = in.readObject();
www.sunilos.com 42
Byte to Char Stream
How to convert byte stream into char stream
o Use InputStreamReader
o InputStreamReader inputStreamReader
= new InputStreamReader(System.in);
www.sunilos.com 43
IO Hierarchy - InputSteam
 java.io.File
 java.io.RandomAccessFile
 java.io.InputStream
o java.io.ByteArrayInputStream
o java.io.FileInputStream
o java.io.FilterInputStream
• java.io.BufferedInputStream
• java.io.DataInputStream
• java.io.
LineNumberInputStream
o java.io.ObjectInputStream
o java.io.
StringBufferInputStream
 java.io.OutputStream
o java.io.ByteArrayOutputStream
o java.io.FileOutputStream
o java.io.FilterOutputStream
• java.io.BufferedOutputStream
• java.io.DataOutputStream
• java.io.PrintStream
o java.io.ObjectOutputStream
www.sunilos.com 44
IO Hierarchy - Reader
 java.io.Reader
o java.io.BufferedReader
• java.io.LineNumberReader
o java.io.CharArrayReader
o java.io.InputStreamReader
• java.io.FileReader
o java.io.StringReader
 java.io.Writer
o java.io.BufferedWriter
o java.io.CharArrayWriter
o java.io.OutputStreamWriter
• java.io.FileWriter
o java.io.PrintWriter
o java.io.StringWriter
Thank You!
12/25/15 www.sunilos.com 45
www.sunilos.com
+91 98273 60504
Ad

More Related Content

What's hot (20)

JDBC
JDBCJDBC
JDBC
Sunil OS
 
Threads V4
Threads  V4Threads  V4
Threads V4
Sunil OS
 
Java Basics V3
Java Basics V3Java Basics V3
Java Basics V3
Sunil OS
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
Sunil OS
 
Log4 J
Log4 JLog4 J
Log4 J
Sunil OS
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
Nilesh Dalvi
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
Sunil OS
 
Java Swing JFC
Java Swing JFCJava Swing JFC
Java Swing JFC
Sunil OS
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
Sony India Software Center
 
07 java collection
07 java collection07 java collection
07 java collection
Abhishek Khune
 
6. static keyword
6. static keyword6. static keyword
6. static keyword
Indu Sharma Bhardwaj
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
Sunil OS
 
Hibernate
Hibernate Hibernate
Hibernate
Sunil OS
 
JavaScript
JavaScriptJavaScript
JavaScript
Sunil OS
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
Vinod Kumar
 
Java IO
Java IOJava IO
Java IO
UTSAB NEUPANE
 
14 file handling
14 file handling14 file handling
14 file handling
APU
 
Resource Bundle
Resource BundleResource Bundle
Resource Bundle
Sunil OS
 
String in java
String in javaString in java
String in java
Ideal Eyes Business College
 
Java I/O
Java I/OJava I/O
Java I/O
Jussi Pohjolainen
 

Viewers also liked (7)

Routing Protocols and Concepts - Chapter 1
Routing Protocols and Concepts - Chapter 1Routing Protocols and Concepts - Chapter 1
Routing Protocols and Concepts - Chapter 1
CAVC
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
pinkpreet_kaur
 
Congestion control in TCP
Congestion control in TCPCongestion control in TCP
Congestion control in TCP
selvakumar_b1985
 
Socket System Calls
Socket System CallsSocket System Calls
Socket System Calls
Avinash Varma Kalidindi
 
TCP congestion control
TCP congestion controlTCP congestion control
TCP congestion control
Shubham Jain
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
Anton Keks
 
Socket programming
Socket programmingSocket programming
Socket programming
chandramouligunnemeda
 
Routing Protocols and Concepts - Chapter 1
Routing Protocols and Concepts - Chapter 1Routing Protocols and Concepts - Chapter 1
Routing Protocols and Concepts - Chapter 1
CAVC
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
pinkpreet_kaur
 
TCP congestion control
TCP congestion controlTCP congestion control
TCP congestion control
Shubham Jain
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
Anton Keks
 
Ad

Similar to Java Input Output and File Handling (20)

file handling c++
file handling c++file handling c++
file handling c++
Guddu Spy
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
Rex Joe
 
Files in c++
Files in c++Files in c++
Files in c++
Selvin Josy Bai Somu
 
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.pdf11_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
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
Kavitha713564
 
Files and streams
Files and streamsFiles and streams
Files and streams
Pranali Chaudhari
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
Eduardo Bergavera
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12
Vince Vo
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
Hamid Ghorbani
 
5java Io
5java Io5java Io
5java Io
Adil Jafri
 
File handling in C++
File handling in C++File handling in C++
File handling in C++
Hitesh Kumar
 
Introduction to files management systems
Introduction to files management systemsIntroduction to files management systems
Introduction to files management systems
araba8
 
File handling in_c
File handling in_cFile handling in_c
File handling in_c
sanya6900
 
working with files
working with filesworking with files
working with files
SangeethaSasi1
 
chapter 2(IO and stream)/chapter 2, IO and stream
chapter 2(IO and stream)/chapter 2, IO and streamchapter 2(IO and stream)/chapter 2, IO and stream
chapter 2(IO and stream)/chapter 2, IO and stream
amarehope21
 
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
AzanMehdi
 
file_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbb
file_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbbfile_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbb
file_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbb
SanskritiGupta39
 
ExtraFileIO.pptx
ExtraFileIO.pptxExtraFileIO.pptx
ExtraFileIO.pptx
NguynThiThanhTho
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
pinkpreet_kaur
 
Data file handling
Data file handlingData file handling
Data file handling
Saurabh Patel
 
file handling c++
file handling c++file handling c++
file handling c++
Guddu Spy
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
Rex Joe
 
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.pdf11_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
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
Kavitha713564
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
Eduardo Bergavera
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12
Vince Vo
 
File handling in C++
File handling in C++File handling in C++
File handling in C++
Hitesh Kumar
 
Introduction to files management systems
Introduction to files management systemsIntroduction to files management systems
Introduction to files management systems
araba8
 
File handling in_c
File handling in_cFile handling in_c
File handling in_c
sanya6900
 
chapter 2(IO and stream)/chapter 2, IO and stream
chapter 2(IO and stream)/chapter 2, IO and streamchapter 2(IO and stream)/chapter 2, IO and stream
chapter 2(IO and stream)/chapter 2, IO and stream
amarehope21
 
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
AzanMehdi
 
file_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbb
file_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbbfile_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbb
file_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbb
SanskritiGupta39
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
pinkpreet_kaur
 
Ad

More from Sunil OS (19)

DJango
DJangoDJango
DJango
Sunil OS
 
PDBC
PDBCPDBC
PDBC
Sunil OS
 
OOP v3
OOP v3OOP v3
OOP v3
Sunil OS
 
Threads v3
Threads v3Threads v3
Threads v3
Sunil OS
 
Exception Handling v3
Exception Handling v3Exception Handling v3
Exception Handling v3
Sunil OS
 
Machine learning ( Part 3 )
Machine learning ( Part 3 )Machine learning ( Part 3 )
Machine learning ( Part 3 )
Sunil OS
 
Machine learning ( Part 2 )
Machine learning ( Part 2 )Machine learning ( Part 2 )
Machine learning ( Part 2 )
Sunil OS
 
Machine learning ( Part 1 )
Machine learning ( Part 1 )Machine learning ( Part 1 )
Machine learning ( Part 1 )
Sunil OS
 
Python Pandas
Python PandasPython Pandas
Python Pandas
Sunil OS
 
Python part2 v1
Python part2 v1Python part2 v1
Python part2 v1
Sunil OS
 
Angular 8
Angular 8 Angular 8
Angular 8
Sunil OS
 
Python Part 1
Python Part 1Python Part 1
Python Part 1
Sunil OS
 
C# Variables and Operators
C# Variables and OperatorsC# Variables and Operators
C# Variables and Operators
Sunil OS
 
C# Basics
C# BasicsC# Basics
C# Basics
Sunil OS
 
Rays Technologies
Rays TechnologiesRays Technologies
Rays Technologies
Sunil OS
 
C++ oop
C++ oopC++ oop
C++ oop
Sunil OS
 
C++
C++C++
C++
Sunil OS
 
C Basics
C BasicsC Basics
C Basics
Sunil OS
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
Sunil OS
 
Threads v3
Threads v3Threads v3
Threads v3
Sunil OS
 
Exception Handling v3
Exception Handling v3Exception Handling v3
Exception Handling v3
Sunil OS
 
Machine learning ( Part 3 )
Machine learning ( Part 3 )Machine learning ( Part 3 )
Machine learning ( Part 3 )
Sunil OS
 
Machine learning ( Part 2 )
Machine learning ( Part 2 )Machine learning ( Part 2 )
Machine learning ( Part 2 )
Sunil OS
 
Machine learning ( Part 1 )
Machine learning ( Part 1 )Machine learning ( Part 1 )
Machine learning ( Part 1 )
Sunil OS
 
Python Pandas
Python PandasPython Pandas
Python Pandas
Sunil OS
 
Python part2 v1
Python part2 v1Python part2 v1
Python part2 v1
Sunil OS
 
Angular 8
Angular 8 Angular 8
Angular 8
Sunil OS
 
Python Part 1
Python Part 1Python Part 1
Python Part 1
Sunil OS
 
C# Variables and Operators
C# Variables and OperatorsC# Variables and Operators
C# Variables and Operators
Sunil OS
 
Rays Technologies
Rays TechnologiesRays Technologies
Rays Technologies
Sunil OS
 

Recently uploaded (20)

How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx   quiz by Ridip HazarikaTHE STG QUIZ GROUP D.pptx   quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
Ridip Hazarika
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
Nguyen Thanh Tu Collection
 
"Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules""Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules"
rupalinirmalbpharm
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
Herbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptxHerbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptx
RAJU THENGE
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Link your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRMLink your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRM
Celine George
 
APM Midlands Region April 2025 Sacha Hind Circulated.pdf
APM Midlands Region April 2025 Sacha Hind Circulated.pdfAPM Midlands Region April 2025 Sacha Hind Circulated.pdf
APM Midlands Region April 2025 Sacha Hind Circulated.pdf
Association for Project Management
 
dynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south Indiadynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south India
PrachiSontakke5
 
Sugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptxSugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptx
Dr. Renu Jangid
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
Kenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 CohortKenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 Cohort
EducationNC
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFAExercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Dr. Nasir Mustafa
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx   quiz by Ridip HazarikaTHE STG QUIZ GROUP D.pptx   quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
Ridip Hazarika
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
Nguyen Thanh Tu Collection
 
"Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules""Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules"
rupalinirmalbpharm
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
Herbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptxHerbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptx
RAJU THENGE
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Link your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRMLink your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRM
Celine George
 
dynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south Indiadynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south India
PrachiSontakke5
 
Sugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptxSugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptx
Dr. Renu Jangid
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
Kenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 CohortKenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 Cohort
EducationNC
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFAExercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Dr. Nasir Mustafa
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 

Java Input Output and File Handling

  • 2. www.sunilos.com 2 Input/Output Concepts  Data Storage o Transient memory : RAM • It is accessed directly by processor. o Persistent Memory: Disk and Tape • It requires I/O operations.  I/O sources and destinations o console, disk, tape, network, etc.  Streams o It represents a sequential stream of bytes. o It hides the details of I/O devices.
  • 3. www.sunilos.com 3 IO Stream– java.io package 101010 101010Byte Array Byte Array 1010 1010ABCD Binary Data •.exe •.jpg •.class Text Data •.txt •.java •.bat ABCDThis is Line This is Line InputStream ByteByte OutputStream BufferedOutputStream BufferedInputStream BufferedWriter BufferedReader Writer Reader Char Line Char Line Byte Byte • FileWriter • PrintWriter • FileReader • InputStreamReader • Scanner • FileOutputStream • ObjectOutputStream • FileInputStream • ObjectInputStream
  • 4. www.sunilos.com 4 Types Of Data  character data o Represented as 1-byte ASCII . o Represented as 2-bytes Unicode within Java programs. The first 128 characters of Unicode are the ASCII characters. o Read by Reader and its subclasses. o Written by Writer and its subclasses. o You can use java.util.Scanner to read characters in JDK1.5 onward.  binary data o Read by InputStream and its subclasses. o Written by OutputStream and its subclasses.
  • 5. www.sunilos.com 5 Attrib.java : c:>java Attrib <fileName> import java.io.File; java.util.Date; public static void main(String[] args) { File f = new File("c:/temp/a.txt”"); // 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(“Length " + f.length() + " bytes long."); } } }
  • 6. www.sunilos.com 6 Representing a File  Class java.io.File represents a file or folder (directory). o Constructors: • public File (String path) • public File (String path, String name) o Interesting methods: • boolean exists() • boolean isDirectory() • boolean isFile() • boolean canRead() • boolean canWrite() • long length() • long lastModified()
  • 7. www.sunilos.com 7 Representing a File (Cont.) More interesting methods: o boolean delete() o boolean renameTo(File dest) o boolean mkdir() o String[] list() o File[] listFiles() o String getName()
  • 8. www.sunilos.com 8 Display file and subdirectories This program displays files and subdirectories of a directory. public static void main(String[] args) { File directory = new File("C:/temp"); //File directory = new File(args[0]); String[] list = directory.list(); for (int i = 0; i < list.length; i++) { System.out.println((i + 1) + " : " + list[i]); } }
  • 9. www.sunilos.com 9 Display only files from a folder public static void main(String[] args) { File directory = new File("C:/temp"); //File directory = new File(args[0]); String[] list = directory.list(); for (int i = 0; i < list.length; i++) { File f = new File(“c:/temp”,list[i]); if(f.isFile()){ System.out.println((i + 1) + " : " + list[i]); } } }
  • 10. www.sunilos.com 10 Display only files from a folder public static void main(String[] args) { File directory = new File("C:/temp"); File[] list = directory.listFiles(); for (int i = 0; i < list.length; i++) { if (list[i].isFile()) { System.out.println((i + 1) + " : " + list[i].getName()); } } }
  • 11. www.sunilos.com 11 FileReader- Read char from a file public static void main(String[] args) throws Exception{ FileReader reader = new FileReader(“c:/test.txt”); int ch = reader.read(); char chr; while(ch != -1){ chr = (char)ch; System.out.print( chr); ch = reader.read(); } }
  • 12. www.sunilos.com 12 Read a file line by line public static void main(String[] args) throws Exception { FileReader reader = new FileReader("c:/test.txt"); BufferedReader br= new BufferedReader(reader); String line = br.readLine(); while (line != null) { System.out.println(line); line = br.readLine(); } reader.close(); }
  • 13. www.sunilos.com 13 Read file by Line 1010 Text Data •.txt •.java •.bat ABCD This is Line BufferedReader FileReader Char LineByte Byte Char Line
  • 14. www.sunilos.com 14 Write to a File public static void main(String[] args) throws Exception { FileWriter writer = new FileWriter("c:/newtest.txt"); PrintWriter pw= new PrintWriter(writer); for (int i = 0; i < 5; i++) { pw.println(i + " : Line"); } pw.close(); writer.close(); System.out.println(“File is successfully written, Pl check c:/newtest.txt "); }
  • 15. www.sunilos.com 15 Write to a File 1010ABCD •Text Data •.txt •.java •.bat This is Line PrintWriter FileWriter Char Line Byte Contains print and println methods Line Char Byte
  • 16. www.sunilos.com 16 Append Text/Bytes in existing File  FileWriter: You may use either constructor to create a FileWriter object to append text in an existing file. o FileWriter(“c:a.txt”,true) o FileWriter(new File(“c:a.txt”),true)  FileOutputStream: You may use either constructor to create a FileOutputStream object to append bytes in an existing binary file. o FileOutputStream (“c:a.jpg”,true) o FileOutputStream (new File(“c:a.jpg”),true)
  • 17. Copy A Text File  String source= "c:/a.txt";  String target = "c:/b.txt";  FileReader reader = new FileReader(source);  FileWriter writer = new FileWriter(target);  int ch = reader.read() ;  while (ch != -1){ o writer.write(ch); o ch = reader.read();  }  writer.close();  reader.close();  System.out.println(source + " is copied to "+ target); www.sunilos.com 17
  • 18. Copy A Binary File  String source= "c:/IMG_0046.JPG";  String target = "c:/baby.jpg";  FileInputStream reader = new FileInputStream(source);  FileOutputStream writer = new FileOutputStream(target);  int ch = reader.read() ;  while (ch != -1){ o writer.write(ch); o ch = reader.read();  }  writer.close();  reader.close();  System.out.println(source + " is copied to "+ target); www.sunilos.com 18
  • 19. Convert Binary to Text Stream Class : InputStreamReader Reads Data From Keyboard o InputStreamReader ir= new InputStreamReader(System.in); www.sunilos.com 19 1010 ABCD CharByte InputStreamReader
  • 20. www.sunilos.com 20 Copycon command  Reads data from keyboard and writes into a file  String target= "c:/temp.txt";  FileWriter writer = new FileWriter(target);  PrintWriter printWriter = new PrintWriter(writer);  InputStreamReader isReader = new InputStreamReader(System.in);  BufferedReader in = new BufferedReader(isReader );  String line = in.readLine();  while (!line.equals("quit")) { o printWriter.print(line); o line = in.readLine();  }  printWriter.close();  isReader.close();
  • 21. www.sunilos.com 21 Serialization  public class Employee implements Serializable {  private int id;  private String firstName;  private String lastName;  private Address add;  private transient String tempValue;  public Employee() { //Default Constructor }  public Employee(int id, String firstName, String lastName) { o this.id = id; o this.firstName = firstName; o this.lastName = lastName;  }  //accessor methods
  • 23. Why Serialization ? When an object is persisted in a file. When an object is sent over the Network. When an object is sent to Hardware. Or in other words when an object is sent Out of JVM. www.sunilos.com 23
  • 24. Persist/Write an Object  FileOutputStream file = new FileOutputStream("c:/object.ser");  ObjectOutputStream out = new ObjectOutputStream(file);  Employee emp = new Employee(10, “Sachin", “10lukar");  out.writeObject(emp);  out.close();  System.out.println("Object is successfully persisted"); www.sunilos.com 24
  • 25. Read an Object www.sunilos.com 25  FileInputStream file= new FileInputStream("c:/object.ser")  ObjectInputStream in = new ObjectInputStream(file);  Employee emp = (Employee) in.readObject();  System.out.println("ID : " + emp.getId());  System.out.println("F Name : " + emp.getFirstName());  System.out.println("L Name : " + emp.getLastName());  System.out.println("Temp Value: " + emp.getTempValue());  NOTE : transient variables will be discarded during serialization
  • 26. www.sunilos.com 26 Write Primitive Data What are primitive data types? o int o double o float o boolean o char Which classes to use? o DataInputStream o DataOutputStream
  • 27. Write Primitive Data  public static void main(String[] args) throws Exception { o FileOutputStream file = new FileOutputStream("c:/primitivedata.dat"); o DataOutputStream out = new DataOutputStream(file); o out.writeInt(1); o out.writeBoolean(true); o out.writeChar('A'); o out.writeDouble(1.2); o out.close(); o file.close() o System.out.println("Primitive Data successfully written");  } www.sunilos.com 27
  • 28. Read Primitive Data  public static void main(String[] args) throws Exception { o FileInputStream file = new FileInputStream("c:/primitivedata.dat"); o DataInputStream in = new DataInputStream(file); o System.out.println(in.readInt()); o System.out.println(in.readBoolean()); o System.out.println(in.readChar()); o System.out.println(in.readDouble()); o in.close();  } www.sunilos.com 28
  • 29. www.sunilos.com 29 Primitive File - Write public static void main(String[] args) throws Exception { long dataPosition = 0; // to be determined later RandomAccessFile in = new RandomAccessFile("datafile.dat", "rw"); // Write to the file. in.writeLong(0); // placeholder in.writeChars("blahblahblah"); dataPosition = in.getFilePointer(); in.writeInt(123); in.writeBytes(“Blahblahblah"); // Rewrite the first byte to reflect updated data position. in.seek(0); in.writeLong(dataPosition); in.close(); }
  • 30. www.sunilos.com 30 Primitive File - Read public static void main(String[] args) throws Exception { long dataPosition = 0; int data = 0; RandomAccessFile raf = new RandomAccessFile("datafile", "r"); // Get the position of the data to read. dataPosition = raf.readLong(); System.out.println("dataPosition : " + dataPosition); // Go to that position. raf.seek(dataPosition); // Read the data. data = raf.readInt(); raf.close(); System.out.println("The data is: " + data); }
  • 31. www.sunilos.com 31 java.util.Scanner  A simple text scanner which can parse primitive data types and strings using regular expressions.  Reads character data as Strings, or converts to primitive values.  Does not throw checked exceptions.  Constructors o Scanner (File source) // reads from a file o Scanner (InputStream source) // reads from a stream o Scanner (String source) // scans a String
  • 32. www.sunilos.com 32 java.util.Scanner Interesting methods: o boolean hasNext() o boolean hasNextInt() o boolean hasNextDouble() o … o String next() o String nextLine() o int nextInt() o double nextDouble()
  • 33. www.sunilos.com 33 Read File By Scanner 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(); }
  • 34. Token A String Breaks string into tokens.  public static void main(String[] args) { o String str = “This is Java, Java is Object Oriented Language, Java is guarantee for job"; o StringTokenizer stn = new StringTokenizer(str, ","); o String token = null; o while (stn.hasMoreElements()) { o token = stn.nextToken(); o System.out.println(“Token is : " + token); o }  } www.sunilos.com 34
  • 35. www.sunilos.com 35 Summary  What is IO Package o java.io  How to represent a File/Directory o File f = new File(“c:/temp/myfile.txt”) • OR o File f = new File(“c:/temp”,”myfile.txt”)
  • 36. www.sunilos.com 36 Summary (Cont.) How to write text data char by char? o FileWriter out = new FileWrite(f); • OR o FileWriter out = new FileWrite (“c:/temp/myfile.txt”); o out.write(‘A’); How to write text data line by line? o PrintWriter pOut = new PrintWriter(out); o pOut.println(“This is Line”);
  • 37. www.sunilos.com 37 Summary (Cont.) How to read text data char by char? o FileReader in = new FileReader(f); • OR o FileReader in = new FileReader (“c:/temp/myfile.txt”); o in.read(); How to read text data line by line? o BufferedReader pIn= new BufferedReader(in); o pIn.readLine(); o Scanner.readLine()
  • 38. www.sunilos.com 38 Summary (Cont.) How to write binary data byte by byte? o FileOutputStream out = new FileOutputStream(f); • OR o FileOutputStream out = new FileOutputStream (“c:/temp/myfile.txt”); o out.write(1); How to write binary data as byte array? o BufferedOutputStream bOut = new BufferedOutputStream (out); o bOut.write(byte[]);
  • 39. www.sunilos.com 39 Summary (Cont.)  How to read binary data byte by byte? o FileInputStream in = new FileInputStream(f); • OR o FileInputStream in = new FileInputStream (“c:/temp/myfile.txt”); o in.read();  How to read binary data as byte array? o BufferedInputStream bIn = new BufferedInputStream (in); o byte[] buffer = new byte[256]; o bIn.read(buffer);
  • 40. www.sunilos.com 40 Summary (Cont.) How to write primitive data? o FileOutputStream file = new FileOutputStream("c:/primitivedata.dat"); o DataOutputStream out = new DataOutputStream(file); How to Read primitive data? o FileInputStream file = new FileInputStream("c:/primitivedata.dat"); o DataInputStream in = new DataInputStream(file);
  • 41. www.sunilos.com 41 Summary (Cont.)  How to persist/write an Object o Make object Serialized o FileOutputStream file = new FileOutputStream("c:/object.ser"); o ObjectOutputStream out = new ObjectOutputStream(file); o out.writeObject(obj);  How to read an Object o FileInputStream file = new FileInputStream("c:/object.ser"); o ObjectInputStream in = new ObjectInputStream(file); o Object obj = in.readObject();
  • 42. www.sunilos.com 42 Byte to Char Stream How to convert byte stream into char stream o Use InputStreamReader o InputStreamReader inputStreamReader = new InputStreamReader(System.in);
  • 43. www.sunilos.com 43 IO Hierarchy - InputSteam  java.io.File  java.io.RandomAccessFile  java.io.InputStream o java.io.ByteArrayInputStream o java.io.FileInputStream o java.io.FilterInputStream • java.io.BufferedInputStream • java.io.DataInputStream • java.io. LineNumberInputStream o java.io.ObjectInputStream o java.io. StringBufferInputStream  java.io.OutputStream o java.io.ByteArrayOutputStream o java.io.FileOutputStream o java.io.FilterOutputStream • java.io.BufferedOutputStream • java.io.DataOutputStream • java.io.PrintStream o java.io.ObjectOutputStream
  • 44. www.sunilos.com 44 IO Hierarchy - Reader  java.io.Reader o java.io.BufferedReader • java.io.LineNumberReader o java.io.CharArrayReader o java.io.InputStreamReader • java.io.FileReader o java.io.StringReader  java.io.Writer o java.io.BufferedWriter o java.io.CharArrayWriter o java.io.OutputStreamWriter • java.io.FileWriter o java.io.PrintWriter o java.io.StringWriter
  • 45. Thank You! 12/25/15 www.sunilos.com 45 www.sunilos.com +91 98273 60504