SlideShare a Scribd company logo
Java & JEE Training
Session 22 – Java IO – Files, Streams and
Object Serialization
Page 1Classification: Restricted
Agenda
• Java IO
• Files
• Streams
• Byte-based
• Character-based
• Object Serialization
Page 2Classification: Restricted
Files and Streams
• Java views each file as a sequential stream of bytes
• Every operating system provides a mechanism to determine the end of a
file, such as an end-of-file marker or a count of the total bytes in the file
that is recorded in a system-maintained administrative data structure.
• A Java program simply receives an indication from the operating system
when it reaches the end of the stream
Page 3Classification: Restricted
Files and Streams Contd..
• File streams can be used to input and output data as bytes or characters.
• Streams that input and output bytes are known as byte-based streams,
representing data in its binary format.
• Streams that input and output characters are known as character-based
streams, representing data as a sequence of characters.
• Files that are created using byte-based streams are referred to as binary
files.
• Files created using character-based streams are referred to as text files.
Text files can be read by text editors.
• Binary files are read by programs that understand the specific content of
the file and the ordering of that content.
Page 4Classification: Restricted
Files and Streams (Contd.)
• A Java program opens a file by creating an object and associating a stream
of bytes or characters with it.
• Can also associate streams with different devices.
• Java creates three stream objects when a program begins executing
• System.in (the standard input stream object) normally inputs bytes from
the keyboard
• System.out (the standard output stream object) normally outputs
character data to the screen
• System.err (the standard error stream object) normally outputs
character-based error messages to the screen.
Page 5Classification: Restricted
Files and Streams (Contd.)
• Java programs perform file processing by using classes from package
java.io.
• Includes definitions for stream classes
• FileInputStream (for byte-based input from a file)
• FileOutputStream (for byte-based output to a file)
• FileReader (for character-based input from a file)
• FileWriter (for character-based output to a file)
• You open a file by creating an object of one these stream classes. The
object’s constructor opens the file.
Page 6Classification: Restricted
Files and Streams (Contd.)
• Can perform input and output of objects or variables of primitive data types
without having to worry about the details of converting such values to byte
format.
• To perform such input and output, objects of classes ObjectInputStream
and ObjectOutputStream can be used together with the byte-based file
stream classes FileInputStream and FileOutputStream.
• The complete hierarchy of classes in package java.io can be viewed in the
online documentation at
• http://java.sun.com/javase/6/docs/api/java/io/package-tree.html
Page 7Classification: Restricted
Class “File”
// Demonstrating the File class.
import java.io.File;
public class FileDemonstration
{
// display information about file user specifies
public void analyzePath( String path )
{
// create File object based on user input
File name = new File( path );
if ( name.exists() ) // if name exists, output information about it
{
// display file (or directory) information
System.out.printf(
"%s%sn%sn%sn%sn%s%sn%s%sn%s%sn%s%sn%s%s",
name.getName(), " exists",
( name.isFile() ? "is a file" : "is not a file" ),
( name.isDirectory() ? "is a directory" :
"is not a directory" ),
( name.isAbsolute() ? "is absolute path" :
"is not absolute path" ), "Last modified: ",
name.lastModified(), "Length: ", name.length(),
"Path: ", name.getPath(), "Absolute path: ",
name.getAbsolutePath(), "Parent: ", name.getParent() );
Page 8Classification: Restricted
Class “File”
if ( name.isDirectory() ) // output directory listing
{
String directory[] = name.list();
System.out.println( "nnDirectory contents:n" );
for ( String directoryName : directory )
System.out.printf( "%sn", directoryName );
} // end else
} // end outer if
else // not file or directory, output error message
{
System.out.printf( "%s %s", path, "does not exist." );
} // end else
} // end method analyzePath
} // end class FileDemonstration
Page 9Classification: Restricted
Class File
• A separator character is used to separate directories and files in the path.
• On Windows, the separator character is a backslash ().
• On Linux/UNIX, it’s a forward slash (/).
• Java processes both characters identically in a path name.
• When building Strings that represent path information, use File.separator
to obtain the local computer’s proper separator.
• This constant returns a String consisting of one character—the proper
separator for the system.
Java IO Classes for streaming
Byte-based and Character-based
Page 11Classification: Restricted
java.io classes
• Let us look at some additional interfaces and classes (from package java.io)
for byte-based input and output streams and character-based input and
output streams.
Page 12Classification: Restricted
Standard streams available by default
• System.out: standard output stream
• System.in: standard input stream
• System.err: standard error stream
Page 13Classification: Restricted
InputStream and OutputStream
Page 14Classification: Restricted
Interfaces and Classes for Byte-Based Input and Output
• InputStream and OutputStream are abstract classes that declare methods
for performing byte-based input and output, respectively.
• Concrete implementations:
• FileInputStream and FileOutputStream
• BufferedInputStream and BufferedOutputStream
• ObjectInputStream and ObjectOutputStream
Page 15Classification: Restricted
Interfaces and Classes for Character-Based Input and Output
• The Reader and Writer abstract classes are Unicode two-byte, character-
based streams.
• Most of the byte-based streams have corresponding character-based
concrete Reader or Writer classes.
• Concrete Implementations:
• FileReader and FileWriter
• BufferedReader and BufferedWriter
Page 16Classification: Restricted
Remember..
• Always prefer Buffered I/O over non-buffered I/O. It yields significant
performance improvement over unbuffered I/O, unless proven otherwise.
Object Serialization
Page 18Classification: Restricted
Object Serialization and Deserialization
Page 19Classification: Restricted
Object Serialization
• To read an entire object from or write an entire object to a file, Java
provides object serialization.
• A serialized object is represented as a sequence of bytes that includes the
object’s data and its type information.
• After a serialized object has been written into a file, it can be read from the
file and deserialized to recreate the object in memory.
Page 20Classification: Restricted
Object Serialization
• In a class that implements Serializable, every variable must be Serializable.
• Any one that is not must be declared transient so it will be ignored during
the serialization process.
• All primitive-type variables are serializable.
• For reference-type variables, check the class’s documentation (and possibly
its superclasses) to ensure that the type is Serializable.
• Serializable is a marker interface… it has no methods defined so no method
needs to be overridden. It is just an instruction to the JRE that this class is
Serializable.
Page 21Classification: Restricted
Serialization – How to serialize objects in Java?
• ObjectOutputStream output = new ObjectOutputStream(new
FileOutputStream(“myfileforstoringobject.txt”));
• output.writeObject(record); //record = new instance of the serializable
object
• Caution: It’s a logic error to open an existing file for output when, in fact,
you wish to preserve the file. Class FileOutputStream provides an
overloaded constructor to open and append the data, instead of
overwriting. This will preserve the contents of the file. Try this constructor
as well.
Page 22Classification: Restricted
Deserialization: How to deserialize in Java?
• ObjectInputStream input = new ObjectInputStream(new
FileInputStream(“clients.txt”));
• record = (SerializableClassName) input.readObject(); //record is instance of
the serializable class that we are trying to read from the file.
Page 23Classification: Restricted
Best Practice to avoid resource leaks… < JDK 7
try{
//use buffering
OutputStream file = new FileOutputStream("quarks.ser");
OutputStream buffer = new BufferedOutputStream(file);
ObjectOutput output = new ObjectOutputStream(buffer);
try{
output.writeObject(quarks);
}
finally{
output.close();
}
}
catch(IOException ex){
fLogger.log(Level.SEVERE, "Cannot perform output.", ex);
}
Page 24Classification: Restricted
Best Practice to avoid resource leaks… < JDK 7
//use buffering
OutputStream file = new FileOutputStream("quarks.ser");
OutputStream buffer = new BufferedOutputStream(file);
ObjectOutput output = new ObjectOutputStream(buffer);
try{
output.writeObject(quarks);
} catch(IOException ex){
//handle exception code
}
finally{
try{
output.close();
}catch(IOException ex){
//handle exception code
}
}
Page 25Classification: Restricted
Best practice for closing resources … JDK 7 onwards
• The try-with-resources statement ensures that each resource is closed at the end of the statement,
you do not have to explicitly close the resources.
• Need not explicitly call close()
import java.io.*;
class Test
{
public static void main(String[] args){
try(BufferedReader br=new BufferedReader(new FileReader("myfile.txt")){
String str;
while((str=br.readLine())!=null){
System.out.println(str);
}
}catch(IOException ie){
System.out.println("exception");
}
}
}
Page 26Classification: Restricted
Exercise…
• Write a class in line with AccountRecord.java, but this time make it a
serializable class.
• Create 5 objects and write those into a text file.
• Read each of the 5 objects
Miscellaneous examples
Page 28Classification: Restricted
FileReader and FileWriter Example
import java.io.*;
public class FileRead {
public static void main(String args[])throws IOException {
File file = new File("Hello1.txt");
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write("Thisn isn ann examplen");
writer.flush();
writer.close();
// Creates a FileReader Object
FileReader fr = new FileReader(file);
char [] a = new char[50];
fr.read(a); // reads the content to the array
for(char c : a)
System.out.print(c); // prints the characters one by one
fr.close();
}
}
Page 29Classification: Restricted
File Example: Creating Directories
import java.io.File;
public class CreateDir {
public static void main(String args[]) {
String dirname = "/tmp/user/java/bin";
File d = new File(dirname);
// Create directory now.
d.mkdirs(); //Question: What does mkdirs do?
}
}
Page 30Classification: Restricted
File Example: Listing Directories
import java.io.File;
public class ReadDir {
public static void main(String[] args) {
File file = null;
String[] paths;
try {
// create new file object
file = new File("/tmp");
// array of files and directory
paths = file.list();
// for each name in the path array
for(String path:paths) {
// prints filename and directory name
System.out.println(path);
}
}catch(Exception e) {
// if any error occurs
e.printStackTrace();
}
}
}
Page 31Classification: Restricted
File Example: Create a file
import java.io.File;
import java.io.IOException;
public class CreateFileDemo
{
public static void main( String[] args )
{
try {
File file = new File("C:newfile.txt");
/*If file gets created then the createNewFile()
* method would return true or if the file is
* already present it would return false
*/
boolean fvar = file.createNewFile();
if (fvar){
System.out.println("File has been created successfully");
}
else{
System.out.println("File already present at the specified location");
}
} catch (IOException e) {
System.out.println("Exception Occurred:");
e.printStackTrace();
}
}
}
Page 32Classification: Restricted
How to read file in Java – BufferedInputStream
import java.io.*;
public class ReadFileDemo {
public static void main(String[] args) {
//Specify the path of the file here
File file = new File("C://myfile.txt");
BufferedInputStream bis = null;
FileInputStream fis= null;
try
{
//FileInputStream to read the file
fis = new FileInputStream(file);
/*Passed the FileInputStream to BufferedInputStream
*For Fast read using the buffer array.*/
bis = new BufferedInputStream(fis);
/*available() method of BufferedInputStream
* returns 0 when there are no more bytes
* present in the file to be read*/
while( bis.available() > 0 ){
System.out.print((char)bis.read());
}
}
catch(FileNotFoundException fnfe)
{
System.out.println("The specified file not found" + fnfe);
}
catch(IOException ioe)
{
System.out.println("I/O Exception: " + ioe);
}
finally
{
try{
if(bis != null && fis!=null)
{
fis.close();
bis.close();
}
}catch(IOException ioe)
{
System.out.println("Error in InputStream close(): " + ioe);
}
}
}
}
Page 33Classification: Restricted
How to read file in Java using BufferedReader
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileDemo {
public static void main(String[] args) {
BufferedReader br = null;
BufferedReader br2 = null;
try{
br = new BufferedReader(new FileReader("B:myfile.txt"));
//One way of reading the file
System.out.println("Reading the file using readLine() method:");
String contentLine = br.readLine();
while (contentLine != null) {
System.out.println(contentLine);
contentLine = br.readLine();
}
br2 = new BufferedReader(new FileReader("B:myfile2.txt"));
//Second way of reading the file
System.out.println("Reading the file using read() method:");
int num=0;
char ch;
while((num=br2.read()) != -1)
{
ch=(char)num;
System.out.print(ch);
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
finally
{
try {
if (br != null)
br.close();
if (br2 != null)
br2.close();
}
catch (IOException ioe)
{
System.out.println("Error in closing
the BufferedReader");
}
}
}
}
Page 34Classification: Restricted
How to write to file in Java using BufferedWriter
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteFileDemo {
public static void main(String[] args) {
BufferedWriter bw = null;
try {
String mycontent = "This String would be written"
+
" to the specified File";
//Specify the file name and path here
File file = new File("C:/myfile.txt");
/* This logic will make sure that the file
* gets created if it is not present at the
* specified location*/
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
bw = new BufferedWriter(fw);
bw.write(mycontent);
System.out.println("File written Successfully");
} catch (IOException ioe) {
ioe.printStackTrace();
}
finally
{
try{
if(bw!=null)
bw.close();
}catch(Exception ex){
System.out.println("Error in closing the
BufferedWriter"+ex);
}
}
}
}
Page 35Classification: Restricted
Append content to File using FileWriter and BufferedWriter
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
class AppendFileDemo
{
public static void main( String[] args )
{
try{
String content = "This is my content which would
be appended " +
"at the end of the specified file";
//Specify the file name and path here
File file =new File("C://myfile.txt");
/* This logic is to create the file if the
* file is not already present
*/
if(!file.exists()){
file.createNewFile();
}
//Here true is to append the content to file
FileWriter fw = new FileWriter(file,true);
//BufferedWriter writer give better
performance
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
//Closing BufferedWriter Stream
bw.close();
System.out.println("Data successfully
appended at the end of file");
}catch(IOException ioe){
System.out.println("Exception occurred:");
ioe.printStackTrace();
}
}
}
Page 36Classification: Restricted
Append content to File using PrintWriter
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.IOException;
class AppendFileDemo2
{
public static void main( String[] args )
{
try{
File file =new File("C://myfile.txt");
if(!file.exists()){
file.createNewFile();
}
FileWriter fw = new FileWriter(file,true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
//This will add a new line to the file content
pw.println("");
/* Below three statements would add three
* mentioned Strings to the file in new lines.
*/
pw.println("This is first line");
pw.println("This is the second line");
pw.println("This is third line");
pw.close();
System.out.println("Data successfully appended
at the end of file");
}catch(IOException ioe){
System.out.println("Exception occurred:");
ioe.printStackTrace();
}
}
}
Page 37Classification: Restricted
How to delete file in Java – delete() Method
import java.io.File;
public class DeleteFileJavaDemo
{
public static void main(String[] args)
{
try{
//Specify the file name and path
File file = new File("C:myfile.txt");
/*the delete() method returns true if the file is
* deleted successfully else it returns false
*/
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete failed: File didn't delete");
}
}catch(Exception e){
System.out.println("Exception occurred");
e.printStackTrace();
}
}
}
Page 38Classification: Restricted
How to rename file in Java – renameTo() method
import java.io.File;
public class RenameFileJavaDemo
{
public static void main(String[] args)
{
//Old File
File oldfile =new File("C:myfile.txt");
//New File
File newfile =new File("C:mynewfile.txt");
/*renameTo() return boolean value
* It return true if rename operation is
* successful
*/
boolean flag = oldfile.renameTo(newfile);
if(flag){
System.out.println("File renamed successfully");
}else{
System.out.println("Rename operation failed");
}
}
}
Page 39Classification: Restricted
How to Compress a File in GZIP Format
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
public class GZipExample
{
public static void main( String[] args )
{
GZipExample zipObj = new GZipExample();
zipObj.gzipMyFile();
}
public void gzipMyFile(){
byte[] buffer = new byte[1024];
try{
//Specify Name and Path of Output GZip file here
GZIPOutputStream gos =
new GZIPOutputStream(new FileOutputStream("B://Java/Myfile.gz"));
//Specify location of Input file here
FileInputStream fis =
new FileInputStream("B://Java/Myfile.txt");
//Reading from input file and writing to output GZip file
int length;
while ((length = fis.read(buffer)) > 0) {
/* public void write(byte[] buf, int off, int len):
* Writes array of bytes to the compressed output stream.
* This method will block until all the bytes are written.
* Parameters:
* buf - the data to be written
* off - the start offset of the data
* len - the length of the data
*/
gos.write(buffer, 0, length);
}
fis.close();
/* public void finish(): Finishes writing compressed
* data to the output stream without closing the
* underlying stream.
*/
gos.finish();
gos.close();
System.out.println("File Compressed!!");
}catch(IOException ioe){
ioe.printStackTrace();
}
}
}
Page 40Classification: Restricted
How to Copy a File to another File in Java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyExample
{
public static void main(String[] args)
{
FileInputStream instream = null;
FileOutputStream outstream = null;
try{
File infile =new File("C:MyInputFile.txt");
File outfile =new File("C:MyOutputFile.txt");
instream = new FileInputStream(infile);
outstream = new FileOutputStream(outfile);
byte[] buffer = new byte[1024];
int length;
/*copying the contents from input stream to
* output stream using read and write methods
*/
while ((length = instream.read(buffer)) > 0){
outstream.write(buffer, 0, length);
}
//Closing the input/output file streams
instream.close();
outstream.close();
System.out.println("File copied successfully!!");
}catch(IOException ioe){
ioe.printStackTrace();
}
}
}
Page 41Classification: Restricted
How to make a File Read Only in Java
import java.io.File;
import java.io.IOException;
public class ReadOnlyChangeExample
{
public static void main(String[] args) throws IOException
{
File myfile = new File("C://Myfile.txt");
//making the file read only
boolean flag = myfile.setReadOnly();
if (flag==true)
{
System.out.println("File successfully converted to Read only mode!!");
}
else
{
System.out.println("Unsuccessful Operation!!");
}
}
}
Page 42Classification: Restricted
How to check if a File is hidden in Java
import java.io.File;
import java.io.IOException;
public class HiddenPropertyCheck
{
public static void main(String[] args) throws IOException, SecurityException
{
// Provide the complete file path here
File file = new File("c:/myfile.txt");
if(file.isHidden()){
System.out.println("The specified file is hidden");
}else{
System.out.println("The specified file is not hidden");
}
}
}
Page 43Classification: Restricted
Topics to be covered in next session
• File IO Continued
• Intro to JDBC (Java Database Connectivity)
Page 44Classification: Restricted
Thank you!

More Related Content

What's hot

Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architecture
Anurag
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer Reference
Muthuselvam RS
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
kamal kotecha
 
Hibernate in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
Akshay Ballarpure
 
Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2
PawanMM
 
Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginners
Rahul Jain
 
Struts 2 - Hibernate Integration
Struts 2 - Hibernate Integration Struts 2 - Hibernate Integration
Struts 2 - Hibernate Integration
Hitesh-Java
 
Hibernate tutorial
Hibernate tutorialHibernate tutorial
Hibernate tutorial
Mumbai Academisc
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
Aneega
 
JDBC
JDBCJDBC
Struts 2 - Introduction
Struts 2 - Introduction Struts 2 - Introduction
Struts 2 - Introduction
Hitesh-Java
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
Manav Prasad
 
jsf2 Notes
jsf2 Notesjsf2 Notes
jsf2 Notes
Rajiv Gupta
 
JSP - Part 2 (Final)
JSP - Part 2 (Final) JSP - Part 2 (Final)
JSP - Part 2 (Final)
Hitesh-Java
 
Hibernate
HibernateHibernate
Hibernate
VISHAL DONGA
 
Session 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI BeansSession 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI Beans
PawanMM
 
Hibernate
HibernateHibernate
Hibernate
Prashant Kalkar
 
Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2
Fahad Golra
 
Spring (1)
Spring (1)Spring (1)
Spring (1)
Aneega
 

What's hot (19)

Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architecture
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer Reference
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
 
Hibernate in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
 
Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2
 
Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginners
 
Struts 2 - Hibernate Integration
Struts 2 - Hibernate Integration Struts 2 - Hibernate Integration
Struts 2 - Hibernate Integration
 
Hibernate tutorial
Hibernate tutorialHibernate tutorial
Hibernate tutorial
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
JDBC
JDBCJDBC
JDBC
 
Struts 2 - Introduction
Struts 2 - Introduction Struts 2 - Introduction
Struts 2 - Introduction
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
jsf2 Notes
jsf2 Notesjsf2 Notes
jsf2 Notes
 
JSP - Part 2 (Final)
JSP - Part 2 (Final) JSP - Part 2 (Final)
JSP - Part 2 (Final)
 
Hibernate
HibernateHibernate
Hibernate
 
Session 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI BeansSession 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI Beans
 
Hibernate
HibernateHibernate
Hibernate
 
Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2
 
Spring (1)
Spring (1)Spring (1)
Spring (1)
 

Similar to Java IO, Serialization

CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
VithalReddy3
 
Advanced programming ch2
Advanced programming ch2Advanced programming ch2
Advanced programming ch2
Gera Paulos
 
05io
05io05io
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
Victer Paul
 
Java I/O
Java I/OJava I/O
JAVA
JAVAJAVA
ASP.NET Session 7
ASP.NET Session 7ASP.NET Session 7
ASP.NET Session 7
Sisir Ghosh
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
teach4uin
 
Input output streams
Input output streamsInput output streams
Input output streams
Parthipan Parthi
 
inputoutputstreams-140612032817-phpapp02.pdf
inputoutputstreams-140612032817-phpapp02.pdfinputoutputstreams-140612032817-phpapp02.pdf
inputoutputstreams-140612032817-phpapp02.pdf
hemanth248901
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
Hamid Ghorbani
 
Input/Output Exploring java.io
Input/Output Exploring java.ioInput/Output Exploring java.io
Input/Output Exploring java.io
NilaNila16
 
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsJedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Don Bosco BSIT
 
Java
JavaJava
Java program file I/O
Java program file I/OJava program file I/O
Java program file I/O
Nem Sothea
 
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & OutputItp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
phanleson
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
HindAlmisbahi
 
Input & output
Input & outputInput & output
Input & output
SAIFUR RAHMAN
 
Unit No 5 Files and Database Connectivity.pptx
Unit No 5 Files and Database Connectivity.pptxUnit No 5 Files and Database Connectivity.pptx
Unit No 5 Files and Database Connectivity.pptx
DrYogeshDeshmukh1
 
Java Day-6
Java Day-6Java Day-6
Java Day-6
People Strategists
 

Similar to Java IO, Serialization (20)

CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
 
Advanced programming ch2
Advanced programming ch2Advanced programming ch2
Advanced programming ch2
 
05io
05io05io
05io
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
 
Java I/O
Java I/OJava I/O
Java I/O
 
JAVA
JAVAJAVA
JAVA
 
ASP.NET Session 7
ASP.NET Session 7ASP.NET Session 7
ASP.NET Session 7
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
Input output streams
Input output streamsInput output streams
Input output streams
 
inputoutputstreams-140612032817-phpapp02.pdf
inputoutputstreams-140612032817-phpapp02.pdfinputoutputstreams-140612032817-phpapp02.pdf
inputoutputstreams-140612032817-phpapp02.pdf
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Input/Output Exploring java.io
Input/Output Exploring java.ioInput/Output Exploring java.io
Input/Output Exploring java.io
 
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsJedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io Streams
 
Java
JavaJava
Java
 
Java program file I/O
Java program file I/OJava program file I/O
Java program file I/O
 
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & OutputItp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
Input & output
Input & outputInput & output
Input & output
 
Unit No 5 Files and Database Connectivity.pptx
Unit No 5 Files and Database Connectivity.pptxUnit No 5 Files and Database Connectivity.pptx
Unit No 5 Files and Database Connectivity.pptx
 
Java Day-6
Java Day-6Java Day-6
Java Day-6
 

More from Hitesh-Java

Spring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVCSpring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVC
Hitesh-Java
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Hitesh-Java
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
Hitesh-Java
 
Inner Classes
Inner Classes Inner Classes
Inner Classes
Hitesh-Java
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps
Hitesh-Java
 
Review Session - Part -2
Review Session - Part -2Review Session - Part -2
Review Session - Part -2
Hitesh-Java
 
Review Session and Attending Java Interviews
Review Session and Attending Java Interviews Review Session and Attending Java Interviews
Review Session and Attending Java Interviews
Hitesh-Java
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
Hitesh-Java
 
Collections - Sorting, Comparing Basics
Collections - Sorting, Comparing Basics Collections - Sorting, Comparing Basics
Collections - Sorting, Comparing Basics
Hitesh-Java
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
Hitesh-Java
 
Object Class
Object Class Object Class
Object Class
Hitesh-Java
 
Exception Handling - Continued
Exception Handling - Continued Exception Handling - Continued
Exception Handling - Continued
Hitesh-Java
 
Exception Handling - Part 1
Exception Handling - Part 1 Exception Handling - Part 1
Exception Handling - Part 1
Hitesh-Java
 
OOPs with Java - Packaging and Access Modifiers
OOPs with Java - Packaging and Access Modifiers OOPs with Java - Packaging and Access Modifiers
OOPs with Java - Packaging and Access Modifiers
Hitesh-Java
 
OOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and InterfacesOOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and Interfaces
Hitesh-Java
 
OOP with Java - Part 3
OOP with Java - Part 3OOP with Java - Part 3
OOP with Java - Part 3
Hitesh-Java
 
OOP with Java - Continued
OOP with Java - Continued OOP with Java - Continued
OOP with Java - Continued
Hitesh-Java
 
Intro to Object Oriented Programming with Java
Intro to Object Oriented Programming with Java Intro to Object Oriented Programming with Java
Intro to Object Oriented Programming with Java
Hitesh-Java
 
Practice Session
Practice Session Practice Session
Practice Session
Hitesh-Java
 
Strings in Java
Strings in Java Strings in Java
Strings in Java
Hitesh-Java
 

More from Hitesh-Java (20)

Spring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVCSpring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVC
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
 
Inner Classes
Inner Classes Inner Classes
Inner Classes
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps
 
Review Session - Part -2
Review Session - Part -2Review Session - Part -2
Review Session - Part -2
 
Review Session and Attending Java Interviews
Review Session and Attending Java Interviews Review Session and Attending Java Interviews
Review Session and Attending Java Interviews
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
 
Collections - Sorting, Comparing Basics
Collections - Sorting, Comparing Basics Collections - Sorting, Comparing Basics
Collections - Sorting, Comparing Basics
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
 
Object Class
Object Class Object Class
Object Class
 
Exception Handling - Continued
Exception Handling - Continued Exception Handling - Continued
Exception Handling - Continued
 
Exception Handling - Part 1
Exception Handling - Part 1 Exception Handling - Part 1
Exception Handling - Part 1
 
OOPs with Java - Packaging and Access Modifiers
OOPs with Java - Packaging and Access Modifiers OOPs with Java - Packaging and Access Modifiers
OOPs with Java - Packaging and Access Modifiers
 
OOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and InterfacesOOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and Interfaces
 
OOP with Java - Part 3
OOP with Java - Part 3OOP with Java - Part 3
OOP with Java - Part 3
 
OOP with Java - Continued
OOP with Java - Continued OOP with Java - Continued
OOP with Java - Continued
 
Intro to Object Oriented Programming with Java
Intro to Object Oriented Programming with Java Intro to Object Oriented Programming with Java
Intro to Object Oriented Programming with Java
 
Practice Session
Practice Session Practice Session
Practice Session
 
Strings in Java
Strings in Java Strings in Java
Strings in Java
 

Recently uploaded

Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
Recommendation System using RAG Architecture
Recommendation System using RAG ArchitectureRecommendation System using RAG Architecture
Recommendation System using RAG Architecture
fredae14
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
Edge AI and Vision Alliance
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Wask
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 

Recently uploaded (20)

Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
Recommendation System using RAG Architecture
Recommendation System using RAG ArchitectureRecommendation System using RAG Architecture
Recommendation System using RAG Architecture
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 

Java IO, Serialization

  • 1. Java & JEE Training Session 22 – Java IO – Files, Streams and Object Serialization
  • 2. Page 1Classification: Restricted Agenda • Java IO • Files • Streams • Byte-based • Character-based • Object Serialization
  • 3. Page 2Classification: Restricted Files and Streams • Java views each file as a sequential stream of bytes • Every operating system provides a mechanism to determine the end of a file, such as an end-of-file marker or a count of the total bytes in the file that is recorded in a system-maintained administrative data structure. • A Java program simply receives an indication from the operating system when it reaches the end of the stream
  • 4. Page 3Classification: Restricted Files and Streams Contd.. • File streams can be used to input and output data as bytes or characters. • Streams that input and output bytes are known as byte-based streams, representing data in its binary format. • Streams that input and output characters are known as character-based streams, representing data as a sequence of characters. • Files that are created using byte-based streams are referred to as binary files. • Files created using character-based streams are referred to as text files. Text files can be read by text editors. • Binary files are read by programs that understand the specific content of the file and the ordering of that content.
  • 5. Page 4Classification: Restricted Files and Streams (Contd.) • A Java program opens a file by creating an object and associating a stream of bytes or characters with it. • Can also associate streams with different devices. • Java creates three stream objects when a program begins executing • System.in (the standard input stream object) normally inputs bytes from the keyboard • System.out (the standard output stream object) normally outputs character data to the screen • System.err (the standard error stream object) normally outputs character-based error messages to the screen.
  • 6. Page 5Classification: Restricted Files and Streams (Contd.) • Java programs perform file processing by using classes from package java.io. • Includes definitions for stream classes • FileInputStream (for byte-based input from a file) • FileOutputStream (for byte-based output to a file) • FileReader (for character-based input from a file) • FileWriter (for character-based output to a file) • You open a file by creating an object of one these stream classes. The object’s constructor opens the file.
  • 7. Page 6Classification: Restricted Files and Streams (Contd.) • Can perform input and output of objects or variables of primitive data types without having to worry about the details of converting such values to byte format. • To perform such input and output, objects of classes ObjectInputStream and ObjectOutputStream can be used together with the byte-based file stream classes FileInputStream and FileOutputStream. • The complete hierarchy of classes in package java.io can be viewed in the online documentation at • http://java.sun.com/javase/6/docs/api/java/io/package-tree.html
  • 8. Page 7Classification: Restricted Class “File” // Demonstrating the File class. import java.io.File; public class FileDemonstration { // display information about file user specifies public void analyzePath( String path ) { // create File object based on user input File name = new File( path ); if ( name.exists() ) // if name exists, output information about it { // display file (or directory) information System.out.printf( "%s%sn%sn%sn%sn%s%sn%s%sn%s%sn%s%sn%s%s", name.getName(), " exists", ( name.isFile() ? "is a file" : "is not a file" ), ( name.isDirectory() ? "is a directory" : "is not a directory" ), ( name.isAbsolute() ? "is absolute path" : "is not absolute path" ), "Last modified: ", name.lastModified(), "Length: ", name.length(), "Path: ", name.getPath(), "Absolute path: ", name.getAbsolutePath(), "Parent: ", name.getParent() );
  • 9. Page 8Classification: Restricted Class “File” if ( name.isDirectory() ) // output directory listing { String directory[] = name.list(); System.out.println( "nnDirectory contents:n" ); for ( String directoryName : directory ) System.out.printf( "%sn", directoryName ); } // end else } // end outer if else // not file or directory, output error message { System.out.printf( "%s %s", path, "does not exist." ); } // end else } // end method analyzePath } // end class FileDemonstration
  • 10. Page 9Classification: Restricted Class File • A separator character is used to separate directories and files in the path. • On Windows, the separator character is a backslash (). • On Linux/UNIX, it’s a forward slash (/). • Java processes both characters identically in a path name. • When building Strings that represent path information, use File.separator to obtain the local computer’s proper separator. • This constant returns a String consisting of one character—the proper separator for the system.
  • 11. Java IO Classes for streaming Byte-based and Character-based
  • 12. Page 11Classification: Restricted java.io classes • Let us look at some additional interfaces and classes (from package java.io) for byte-based input and output streams and character-based input and output streams.
  • 13. Page 12Classification: Restricted Standard streams available by default • System.out: standard output stream • System.in: standard input stream • System.err: standard error stream
  • 15. Page 14Classification: Restricted Interfaces and Classes for Byte-Based Input and Output • InputStream and OutputStream are abstract classes that declare methods for performing byte-based input and output, respectively. • Concrete implementations: • FileInputStream and FileOutputStream • BufferedInputStream and BufferedOutputStream • ObjectInputStream and ObjectOutputStream
  • 16. Page 15Classification: Restricted Interfaces and Classes for Character-Based Input and Output • The Reader and Writer abstract classes are Unicode two-byte, character- based streams. • Most of the byte-based streams have corresponding character-based concrete Reader or Writer classes. • Concrete Implementations: • FileReader and FileWriter • BufferedReader and BufferedWriter
  • 17. Page 16Classification: Restricted Remember.. • Always prefer Buffered I/O over non-buffered I/O. It yields significant performance improvement over unbuffered I/O, unless proven otherwise.
  • 19. Page 18Classification: Restricted Object Serialization and Deserialization
  • 20. Page 19Classification: Restricted Object Serialization • To read an entire object from or write an entire object to a file, Java provides object serialization. • A serialized object is represented as a sequence of bytes that includes the object’s data and its type information. • After a serialized object has been written into a file, it can be read from the file and deserialized to recreate the object in memory.
  • 21. Page 20Classification: Restricted Object Serialization • In a class that implements Serializable, every variable must be Serializable. • Any one that is not must be declared transient so it will be ignored during the serialization process. • All primitive-type variables are serializable. • For reference-type variables, check the class’s documentation (and possibly its superclasses) to ensure that the type is Serializable. • Serializable is a marker interface… it has no methods defined so no method needs to be overridden. It is just an instruction to the JRE that this class is Serializable.
  • 22. Page 21Classification: Restricted Serialization – How to serialize objects in Java? • ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(“myfileforstoringobject.txt”)); • output.writeObject(record); //record = new instance of the serializable object • Caution: It’s a logic error to open an existing file for output when, in fact, you wish to preserve the file. Class FileOutputStream provides an overloaded constructor to open and append the data, instead of overwriting. This will preserve the contents of the file. Try this constructor as well.
  • 23. Page 22Classification: Restricted Deserialization: How to deserialize in Java? • ObjectInputStream input = new ObjectInputStream(new FileInputStream(“clients.txt”)); • record = (SerializableClassName) input.readObject(); //record is instance of the serializable class that we are trying to read from the file.
  • 24. Page 23Classification: Restricted Best Practice to avoid resource leaks… < JDK 7 try{ //use buffering OutputStream file = new FileOutputStream("quarks.ser"); OutputStream buffer = new BufferedOutputStream(file); ObjectOutput output = new ObjectOutputStream(buffer); try{ output.writeObject(quarks); } finally{ output.close(); } } catch(IOException ex){ fLogger.log(Level.SEVERE, "Cannot perform output.", ex); }
  • 25. Page 24Classification: Restricted Best Practice to avoid resource leaks… < JDK 7 //use buffering OutputStream file = new FileOutputStream("quarks.ser"); OutputStream buffer = new BufferedOutputStream(file); ObjectOutput output = new ObjectOutputStream(buffer); try{ output.writeObject(quarks); } catch(IOException ex){ //handle exception code } finally{ try{ output.close(); }catch(IOException ex){ //handle exception code } }
  • 26. Page 25Classification: Restricted Best practice for closing resources … JDK 7 onwards • The try-with-resources statement ensures that each resource is closed at the end of the statement, you do not have to explicitly close the resources. • Need not explicitly call close() import java.io.*; class Test { public static void main(String[] args){ try(BufferedReader br=new BufferedReader(new FileReader("myfile.txt")){ String str; while((str=br.readLine())!=null){ System.out.println(str); } }catch(IOException ie){ System.out.println("exception"); } } }
  • 27. Page 26Classification: Restricted Exercise… • Write a class in line with AccountRecord.java, but this time make it a serializable class. • Create 5 objects and write those into a text file. • Read each of the 5 objects
  • 29. Page 28Classification: Restricted FileReader and FileWriter Example import java.io.*; public class FileRead { public static void main(String args[])throws IOException { File file = new File("Hello1.txt"); // creates the file file.createNewFile(); // creates a FileWriter Object FileWriter writer = new FileWriter(file); // Writes the content to the file writer.write("Thisn isn ann examplen"); writer.flush(); writer.close(); // Creates a FileReader Object FileReader fr = new FileReader(file); char [] a = new char[50]; fr.read(a); // reads the content to the array for(char c : a) System.out.print(c); // prints the characters one by one fr.close(); } }
  • 30. Page 29Classification: Restricted File Example: Creating Directories import java.io.File; public class CreateDir { public static void main(String args[]) { String dirname = "/tmp/user/java/bin"; File d = new File(dirname); // Create directory now. d.mkdirs(); //Question: What does mkdirs do? } }
  • 31. Page 30Classification: Restricted File Example: Listing Directories import java.io.File; public class ReadDir { public static void main(String[] args) { File file = null; String[] paths; try { // create new file object file = new File("/tmp"); // array of files and directory paths = file.list(); // for each name in the path array for(String path:paths) { // prints filename and directory name System.out.println(path); } }catch(Exception e) { // if any error occurs e.printStackTrace(); } } }
  • 32. Page 31Classification: Restricted File Example: Create a file import java.io.File; import java.io.IOException; public class CreateFileDemo { public static void main( String[] args ) { try { File file = new File("C:newfile.txt"); /*If file gets created then the createNewFile() * method would return true or if the file is * already present it would return false */ boolean fvar = file.createNewFile(); if (fvar){ System.out.println("File has been created successfully"); } else{ System.out.println("File already present at the specified location"); } } catch (IOException e) { System.out.println("Exception Occurred:"); e.printStackTrace(); } } }
  • 33. Page 32Classification: Restricted How to read file in Java – BufferedInputStream import java.io.*; public class ReadFileDemo { public static void main(String[] args) { //Specify the path of the file here File file = new File("C://myfile.txt"); BufferedInputStream bis = null; FileInputStream fis= null; try { //FileInputStream to read the file fis = new FileInputStream(file); /*Passed the FileInputStream to BufferedInputStream *For Fast read using the buffer array.*/ bis = new BufferedInputStream(fis); /*available() method of BufferedInputStream * returns 0 when there are no more bytes * present in the file to be read*/ while( bis.available() > 0 ){ System.out.print((char)bis.read()); } } catch(FileNotFoundException fnfe) { System.out.println("The specified file not found" + fnfe); } catch(IOException ioe) { System.out.println("I/O Exception: " + ioe); } finally { try{ if(bis != null && fis!=null) { fis.close(); bis.close(); } }catch(IOException ioe) { System.out.println("Error in InputStream close(): " + ioe); } } } }
  • 34. Page 33Classification: Restricted How to read file in Java using BufferedReader import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class ReadFileDemo { public static void main(String[] args) { BufferedReader br = null; BufferedReader br2 = null; try{ br = new BufferedReader(new FileReader("B:myfile.txt")); //One way of reading the file System.out.println("Reading the file using readLine() method:"); String contentLine = br.readLine(); while (contentLine != null) { System.out.println(contentLine); contentLine = br.readLine(); } br2 = new BufferedReader(new FileReader("B:myfile2.txt")); //Second way of reading the file System.out.println("Reading the file using read() method:"); int num=0; char ch; while((num=br2.read()) != -1) { ch=(char)num; System.out.print(ch); } } catch (IOException ioe) { ioe.printStackTrace(); } finally { try { if (br != null) br.close(); if (br2 != null) br2.close(); } catch (IOException ioe) { System.out.println("Error in closing the BufferedReader"); } } } }
  • 35. Page 34Classification: Restricted How to write to file in Java using BufferedWriter import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class WriteFileDemo { public static void main(String[] args) { BufferedWriter bw = null; try { String mycontent = "This String would be written" + " to the specified File"; //Specify the file name and path here File file = new File("C:/myfile.txt"); /* This logic will make sure that the file * gets created if it is not present at the * specified location*/ if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file); bw = new BufferedWriter(fw); bw.write(mycontent); System.out.println("File written Successfully"); } catch (IOException ioe) { ioe.printStackTrace(); } finally { try{ if(bw!=null) bw.close(); }catch(Exception ex){ System.out.println("Error in closing the BufferedWriter"+ex); } } } }
  • 36. Page 35Classification: Restricted Append content to File using FileWriter and BufferedWriter import java.io.File; import java.io.FileWriter; import java.io.BufferedWriter; import java.io.IOException; class AppendFileDemo { public static void main( String[] args ) { try{ String content = "This is my content which would be appended " + "at the end of the specified file"; //Specify the file name and path here File file =new File("C://myfile.txt"); /* This logic is to create the file if the * file is not already present */ if(!file.exists()){ file.createNewFile(); } //Here true is to append the content to file FileWriter fw = new FileWriter(file,true); //BufferedWriter writer give better performance BufferedWriter bw = new BufferedWriter(fw); bw.write(content); //Closing BufferedWriter Stream bw.close(); System.out.println("Data successfully appended at the end of file"); }catch(IOException ioe){ System.out.println("Exception occurred:"); ioe.printStackTrace(); } } }
  • 37. Page 36Classification: Restricted Append content to File using PrintWriter import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.IOException; class AppendFileDemo2 { public static void main( String[] args ) { try{ File file =new File("C://myfile.txt"); if(!file.exists()){ file.createNewFile(); } FileWriter fw = new FileWriter(file,true); BufferedWriter bw = new BufferedWriter(fw); PrintWriter pw = new PrintWriter(bw); //This will add a new line to the file content pw.println(""); /* Below three statements would add three * mentioned Strings to the file in new lines. */ pw.println("This is first line"); pw.println("This is the second line"); pw.println("This is third line"); pw.close(); System.out.println("Data successfully appended at the end of file"); }catch(IOException ioe){ System.out.println("Exception occurred:"); ioe.printStackTrace(); } } }
  • 38. Page 37Classification: Restricted How to delete file in Java – delete() Method import java.io.File; public class DeleteFileJavaDemo { public static void main(String[] args) { try{ //Specify the file name and path File file = new File("C:myfile.txt"); /*the delete() method returns true if the file is * deleted successfully else it returns false */ if(file.delete()){ System.out.println(file.getName() + " is deleted!"); }else{ System.out.println("Delete failed: File didn't delete"); } }catch(Exception e){ System.out.println("Exception occurred"); e.printStackTrace(); } } }
  • 39. Page 38Classification: Restricted How to rename file in Java – renameTo() method import java.io.File; public class RenameFileJavaDemo { public static void main(String[] args) { //Old File File oldfile =new File("C:myfile.txt"); //New File File newfile =new File("C:mynewfile.txt"); /*renameTo() return boolean value * It return true if rename operation is * successful */ boolean flag = oldfile.renameTo(newfile); if(flag){ System.out.println("File renamed successfully"); }else{ System.out.println("Rename operation failed"); } } }
  • 40. Page 39Classification: Restricted How to Compress a File in GZIP Format import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.GZIPOutputStream; public class GZipExample { public static void main( String[] args ) { GZipExample zipObj = new GZipExample(); zipObj.gzipMyFile(); } public void gzipMyFile(){ byte[] buffer = new byte[1024]; try{ //Specify Name and Path of Output GZip file here GZIPOutputStream gos = new GZIPOutputStream(new FileOutputStream("B://Java/Myfile.gz")); //Specify location of Input file here FileInputStream fis = new FileInputStream("B://Java/Myfile.txt"); //Reading from input file and writing to output GZip file int length; while ((length = fis.read(buffer)) > 0) { /* public void write(byte[] buf, int off, int len): * Writes array of bytes to the compressed output stream. * This method will block until all the bytes are written. * Parameters: * buf - the data to be written * off - the start offset of the data * len - the length of the data */ gos.write(buffer, 0, length); } fis.close(); /* public void finish(): Finishes writing compressed * data to the output stream without closing the * underlying stream. */ gos.finish(); gos.close(); System.out.println("File Compressed!!"); }catch(IOException ioe){ ioe.printStackTrace(); } } }
  • 41. Page 40Classification: Restricted How to Copy a File to another File in Java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class CopyExample { public static void main(String[] args) { FileInputStream instream = null; FileOutputStream outstream = null; try{ File infile =new File("C:MyInputFile.txt"); File outfile =new File("C:MyOutputFile.txt"); instream = new FileInputStream(infile); outstream = new FileOutputStream(outfile); byte[] buffer = new byte[1024]; int length; /*copying the contents from input stream to * output stream using read and write methods */ while ((length = instream.read(buffer)) > 0){ outstream.write(buffer, 0, length); } //Closing the input/output file streams instream.close(); outstream.close(); System.out.println("File copied successfully!!"); }catch(IOException ioe){ ioe.printStackTrace(); } } }
  • 42. Page 41Classification: Restricted How to make a File Read Only in Java import java.io.File; import java.io.IOException; public class ReadOnlyChangeExample { public static void main(String[] args) throws IOException { File myfile = new File("C://Myfile.txt"); //making the file read only boolean flag = myfile.setReadOnly(); if (flag==true) { System.out.println("File successfully converted to Read only mode!!"); } else { System.out.println("Unsuccessful Operation!!"); } } }
  • 43. Page 42Classification: Restricted How to check if a File is hidden in Java import java.io.File; import java.io.IOException; public class HiddenPropertyCheck { public static void main(String[] args) throws IOException, SecurityException { // Provide the complete file path here File file = new File("c:/myfile.txt"); if(file.isHidden()){ System.out.println("The specified file is hidden"); }else{ System.out.println("The specified file is not hidden"); } } }
  • 44. Page 43Classification: Restricted Topics to be covered in next session • File IO Continued • Intro to JDBC (Java Database Connectivity)