SlideShare a Scribd company logo
1 of 57
Download to read offline
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
1
Day 6
Input/Output Operations
Annotation Basics
Enum
Input/Output Operations
Basic IO
• Java provides a standard way of reading from and writing to files.
• Java defines the two streams, byte stream and character stream to
read and write data .
• Java byte streams are used to perform input and output of 8-bit
bytes.
• Java character streams are used to perform input and output for 16-
bit Unicode.
• To perform the read and write operation, Java provides a set of
classes packed inside java.io package.
Basic IO
• Java provides a set classes inside the java.io package to perfrom I/O
operations.
• The hierarchy of classes in java.io package:
java.lang.Object
java.io.InputStream java.io.BufferedInputStream
java.io.OutputStream java.io.BufferedOutputStream
java.io.Reader java.io.BufferedReader
java.io.Writer java.io.BufferedWriter
InputStream Class
• The InputStream class is used for reading byte streams.
• The hierarchy of InputStream class:
java.io.InputStream
java.io.FileInputStream
java.io.FilterInputStream
java.ioBufferedInputStream
java.io.DataInputStream
InputStream Class (Contd.)
• The following table list the methods in InputStream class:
Return Type Method Name Description
int available() Returns an estimate of the number of bytes that can
be read
void close() Closes the input stream and releases any system
resources associated with the stream.
int read() Reads the next byte of data from the input stream.
int read(byte[] b) Reads some number of bytes from the input stream
and stores them into the buffer array b.
int read(byte[] b, int off, int
len)
Reads up to len bytes of data from the input stream
into an array of bytes.
long skip(long n) Skips over and discards n bytes of data from this
input stream.
OutputStream Class
• The OutputStream class is used for writing byte stream.
• The hierarchy of OutputStream class:
java.io.OutputStream
java.io.FileOutputStream
java.io.FilterOutputStream
java.ioBufferedOutputStream
java.io.DataOutputStream
OutputStream Class (Contd.)
• The following table list the methods in OutputStream class:
Return Type Method Name Description
void close() Closes the input stream and releases any system
resources associated with the stream.
int flush() Flushes this output stream and forces any
buffered output bytes to be written out.
int writ(byte[] b) Writes b.length bytes from the specified byte
array to this output stream.
int write(byte[] b, int off,
int len)
Writes len bytes from the specified byte array
starting at offset off to this output stream.
long Write(int b) Writes the specified byte to this output stream.
Reader Class
• The Reader class is used for reading character streams.
• The hierarchy of Reader class:
java.io.Reader
java.io.InputStreamReader java.io.FileReader
java.ioBufferedReader
Reader Class (Contd.)
• The following table list the methods in Reader class:
Return Type Method Name Description
void close() Closes the input stream and releases any system
resources associated with the stream.
int read() Reads a single character.
int read(char[] b) Reads characters into an array.
int read(char[] b, int off, int
len)
Reads characters into a portion of an array.
int read(CharBuffer target) Attempts to read characters into the specified
character buffer.
long skip(long n) Skips over and discards n bytes of data from this
input stream.
Writer Class
• The Writer class is used for writing character streams.
• The hierarchy of Writer class:
java.io.Writer
java.io.InputStreamWriter java.io.FileWriter
java.io.BufferedWriter
Java.io.PrintWriter
Writer Class (Contd.)
• The following table list the methods in Writer class:
Return Type Method Name Description
close close() Closes the input stream and releases any system
resources associated with the stream.
int flush() Flushes this output stream and forces any
buffered output bytes to be written out.
int writ(char[] b) Writes an array of characters.
int write(char[] b, int off,
int len)
Writes a portion of an array of characters.
long Write(int b) Writes a single character.
void write(String str) Writes a string.
void write(String str, int off,
int len)
Writes a portion of a string.
File Class
• The File class is used to access files, file attributes, and file systems.
• The constructors in File class:
• File(String pathname):Creates a new File instance by converting the given
pathname string into an abstract pathname.
• File(String parent, String child) :Creates a new File instance from a parent
pathname string and a child pathname string.
File Class (Contd.)
• The following table list the methods in File class:
Return Type Method Name Description
boolean createNewFile() Atomically creates a new, empty file named by this abstract
pathname if and only if a file with this name does not yet exist.
boolean delete() Deletes the file or directory denoted by this abstract pathname.
boolean exists() Tests whether the file or directory denoted by this abstract
pathname exists.
String getName() Returns the name of the file or directory denoted by this abstract
pathname.
boolean isFile() Tests whether the file denoted by this abstract pathname is a
normal file.
boolean isDirectory() Tests whether the file denoted by this abstract pathname is a
directory.
long length() Returns the length of the file denoted by this abstract pathname.
File Class (Contd.)
• The following table list the methods in File class:
Return Type Method Name Description
String[] list() Returns an array of strings naming the files and directories in the
directory denoted by this abstract pathname.
boolean mkdir() Creates the directory named by this abstract pathname.
boolean renameTo(File dest) Renames the file denoted by this abstract pathname.
File Class (Contd.)
• An example code to work with File class:
import java.io.*;
public class FileClassDemo {
public static void main(String args[])throws IOException{
File f1=new File("TestFolder");
File f2=new File("TestFile.txt");
File f3=new File("D:FileTest.txt");
File f4=new File("NewFileTest.txt");
f3.createNewFile();
File Class (Contd.)
System.out.println(f2.exists());
System.out.println(f3.getName());
System.out.println(f1.isDirectory());
System.out.println(f2.isFile());
System.out.println(f2.length());
System.out.println();
f3.renameTo(f4);
System.out.println(f4.getName());
f3.delete();
System.out.println(f3.exists());
System.out.println(f4.exists());
}
}
Read and Write Operations
• An example to read String from console and writing back to console
using the InputStreamReader and BufferedReader classes:
import java.io.*;
class ConsoleIOStringDemo {
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(isr);
String name,line;
System.out.println("Enter your name:");
name=input.readLine();
System.out.println("Hi!!!!!!!!!!!!!!!!!!!!!"+name);
}
}
Read and Write Operations (Contd.)
• An example read data from the console until the String quit is entered:
import java.io.*;
class ConsoleIOStringDemo {
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(isr);
String line;
while ((line = input.readLine()) != null) {
if(line.equals("quit")){
System.exit(1);
}
else{
System.out.println(line);
}
}
}
}
Read and Write Operations (Contd.)
• An example to read data from file and print to the console using
FileInputStream class:
import java.io.*;
public class FileInputStreamDemo {
public static void main(String args[])throws IOException{
try(FileInputStream fis = new
FileInputStream("TestFile.txt");){
int i,j=0;
while((i=fis.read())!=-1)
{
if((char)i ==' ')
{
j++;
Read and Write Operations (Contd.)
System.out.println();
}
else {
System.out.print((char)i);
}
}
}
}
}
Read and Write Operations (Contd.)
• An example to read data from console and write to a file using
BufferedReader and FileWriter classes:
import java.io.*;
public class ReadWriteDemo {
public static void main(String args[]) throws
IOException {
String consoleData;
try (BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
FileWriter fw = new
FileWriter("FileTest.txt");) {
Read and Write Operations (Contd.)
while ((consoleData = br.readLine()) != null) {
fw.write(consoleData);
fw.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Read and Write Operations (Contd.)
• An example to read data from file and print to the console using
FileReader and BufferedReader classes:
import java.io.*;
class FileReaderDemo {
public static void main(String args[]) throws Exception {
FileReader fr = new FileReader("TestFile.txt");
BufferedReader br = new BufferedReader(fr);
String s;
while((s = br.readLine()) != null) {
System.out.println(s);
}
fr.close();
}
}
Read and Write Operations (Contd.)
• An example to read file and write into another file using the
FileInputStream and BufferedWriter classes.
import java.io.*;
public class ReadWriteDemo {
public static void main(String st[]) throws Exception {
int i;
FileInputStream fis = new FileInputStream("TestFile.txt");
BufferedWriter bw = new BufferedWriter(new
OutputStreamWriter(new FileOutputStream("FOSFile.Txt")));
while ((i = fis.read()) != -1) {
bw.flush();
bw.write(i);
}
}
}
Serialization
• Serialization is a process in which current state of Object will be saved
in stream of bytes.
• Serialization is used when data needs to be sent over network or
stored in files.
• Classes ObjectInputStream and ObjectOutputStream are high-level
streams that contain the methods for serializing and deserializing an
object.
• The readObject() method is used to read an object.
• The writeObject() method is used write an object
Serialization (Contd.)
• An example to implement serialization:
import java.io.Serializable;
public class Employee implements Serializable{
int employeeId;
String employeeName;
String department;
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
Serialization (Contd.)
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
}
Serialization (Contd.)
import java.io.*;
public class SerializeMain {
public static void main(String[] args) {
Employee emp = new Employee();
emp.setEmployeeId(101);
emp.setEmployeeName(“Raj");
emp.setDepartment("CS");
Serialization (Contd.)
try
{
FileOutputStream fileOut = new
FileOutputStream("d:employee.txt");
ObjectOutputStream outStream = new
ObjectOutputStream(fileOut);
outStream.writeObject(emp);
outStream.close();
fileOut.close();
}catch(IOException i)
{
i.printStackTrace();
}
}
}
Serialization (Contd.)
import java.io.*;
public class DeserializeMain {
public static void main(String[] args) {
Employee emp = null;
try
{
FileInputStream fileIn =new
FileInputStream("D:employee.txt");
ObjectInputStream in = new ObjectInputStream(fileIn);
emp = (Employee) in.readObject();
in.close();
fileIn.close();
}
Serialization (Contd.)
catch(IOException i)
{
i.printStackTrace();
return;
}catch(ClassNotFoundException c)
{
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Emp id: " + emp.getEmployeeId());
System.out.println("Name: " + emp.getEmployeeName());
System.out.println("Department: " + emp.getDepartment());
}
}
Annotations
Annotations Basics
• Annotations are meta data that provide information about the code.
• Annotations are not a part of code.
• Annotations can be used to mark Java elements, such as package,
constructors, methods, fields, parameters and variables, within the
code.
• Annotations allows the compiler and JVM to extract the program
behavior and generate the interdependent code when required.
• An annotation is prefixed with @ symbol.
Built-in Java Annotations
• Java provides a set of built-in annotations.
• These built-in annotations can be categorized in as:
• Annotations used by the Java language
• Annotations applied to other annotation
• The annotations used by the Java language are defined inside the
java.lang package.
• The annotations applied to other annotation are defined inside the
java.lang.annotation package. These annotations are also called as
meta-annotation.
• The meta-annotations are mostly used with user-defined
annotations.
Built-in Java Annotations (Contd.)
• The commonly used annotation by Java language are:
• @Override
• @SuppressWarnings
• The commonly used annotations applied to other annotation are:
• @Retention
• @Target
• @Inherited
• @Documented
Built-in Java Annotations (Contd.)
• @Override: Annotation is used to inform the compiler that the
method using the annotation is an overridden method.
• Consider the following code snippet:
class Base{
void display(){
}
}
class Sub extends Base{
@Override
void display(){
}
}
Built-in Java Annotations (Contd.)
• In the preceding code, if the method using the annotation is not a overridden
method then a compilation error will be raised.
• @SuppressWarnings: Annotation is used to inform the compiler to
suppress warnings raised by the method using the annotation.
• Consider the following code:
void getData()throws IOException{
DataInputStream dis=new
DataInputStream(System.in);
String s=dis.readLine();
}
Built-in Java Annotations (Contd.)
• The preceding code will raise a warning because the readLine() method is a
deprecated method. This warning can be suppressed by adding the following
statement before the method definition:
@SuppressWarnings("deprecation")
• Here, deprecation is the warning category.
• The @SuppressWarnings annotation can accept the warning
categories, deprecation and unchecked.
• To suppress multiple categories of warnings the following statement
is used:
@SuppressWarnings({"unchecked", "deprecation"})
Built-in Java Annotations (Contd.)
• @Retention: Annotation is used to specify how the marked
annotation is stored. This annotation accepts one of the following
retention policy as argument:
• RetentionPolicy.SOURCE – The marked annotation is retained only in the
source level and is ignored by the compiler.
• RetentionPolicy.CLASS – The marked annotation is retained by the compiler at
compile time, but is ignored by the JVM.
• RetentionPolicy.RUNTIME – The marked annotation is retained by the JVM so
it can be used by the runtime environment.
Built-in Java Annotations (Contd.)
• @Documented :Annotation is used to indicates that the annotation should
be documented.
• @Target: Annotation is used to restrict the usage of the annotation on
certain Java elements. A target annotation can accept one of the following
element types as its argument:
• ElementType.ANNOTATION_TYPE - Can be applied to an annotation type.
• ElementType.CONSTRUCTOR - Can be applied to a constructor.
• ElementType.FIELD - Can be applied to a field or property.
• ElementType.LOCAL_VARIABLE - Can be applied to a local variable.
• ElementType.METHOD - Can be applied to a method-level annotation.
• ElementType.PACKAGE - Can be applied to a package declaration.
• ElementType.PARAMETER - Can be applied to the parameters of a method.
• ElementType.TYPE - Can be applied to any element of a class.
Built-in Java Annotations (Contd.)
• @Inherited: Annotation is used to indicate that the annotation
type is automatically inherited. When the user queries the
annotation type and the class has no annotation the defined type,
then the superclass is queried for the annotation type. The
@Inherited annotation is applied only to class declarations.
User-defined Annotations
• Java allows to create a user-defined annotation.
• The @interface element is used to declare an annotation.
• An example to create a user-defined annotation:
public abstract @interface DescAnnotation {
String description();
}
• An example to use the user defined annotation:
@DescAnnotation(description="AnnotationDemo Class")
public class AnnotationsDemo {
@DescAnnotation(description="Display method")
void display(){
}
User-defined Annotations (Contd.)
• The annotations can have any number of fields.
• An example to create a user-defined annotation with multiple fields:
public abstract @interface DescAnnotation {
String description();
int version();
}
• The class elements using the preceding annotation should define
both fields else an compilation error will be raised.
User-defined Annotations (Contd.)
• An example to create a user-defined annotation with default field
value:
public abstract @interface DescAnnotation {
String description();
int version() default 1;
}
• The class elements using the preceding annotation can omit the
definition of version field.
User-defined Annotations (Contd.)
• An example to create a user-defined annotation with @Retention:
import java.lang.annotation.*;
@Retention(RetentionPolicy.CLASS)
public abstract @interface DescAnnotation {
String description();
int version() default 1;
}
• The DescAnnotation annotation will be embedded into the generated
class file.
User-defined Annotations (Contd.)
• An example to create a user-defined annotation with @Documented:
import java.lang.annotation.*;
@Documented
public abstract @interface DescAnnotation {
String description();
int version() default 1;
}
• The DescAnnotation annotation will be included into Java documents
generated by Java document generator tools.
User-defined Annotations (Contd.)
• An example to create a user-defined annotation with @Target:
import java.lang.annotation.*;
@Target({ ElementType.FIELD, ElementType.METHOD})
public abstract @interface DescAnnotation {
String description();
int version() default 1;
}
• If the preceding annotation is used with elements other than method
or field, a compilation error will be raised.
User-defined Annotations (Contd.)
• An example to create a user-defined annotation with @@Inherited:
import java.lang.annotation.*;
@Inherited
public abstract @interface DescAnnotation {
String description();
int version() default 1;
}
• If the preceding annotation is applied to base class then this
annotation is also available to the sub class.
Enum
• An enum type is a special data type that allows to create a set of constants.
• An enum is defined using the enum keyword.
• An enum is created when all the possible values of a data set is know.
• An example to create a enum:
public enum PaperSize {
A0,A1,A2,A3,A4,A5,A6,A7,A8
}
• You can create a variable of enum type as shown in the following code
snippet:
PaperSize ps=PaperSize.A4;
Enum (Contd.)
• An enum can be defined inside or outside the class.
• The enum defined outside class can use only public access modifier.
However, the enum declared inside the class can use all the four
access modifier.
• An enum can declare variables and define constructors and methods.
• An example to define enum with variables, constructor, and methods:
public enum PaperSize {
A0(841,1189),A1(594,841),A2(420,594),A3(
297,420),A4(210,297),A5(148,210),A6(105,148),A7(74,105
),A8(52,74);
Enum (Contd.)
int dim1,dim2;
public int getDim1() {
return dim1;
}
public void setDim1(int dim1) {
this.dim1 = dim1;
}
public int getDim2() {
return dim2;
}
public void setDim2(int dim2) {
this.dim2 = dim2;
}
PaperSize(int dim1,int dim2){
this.dim1=dim1;
this.dim2=dim2;
}
}
Enum (Contd.)
public class EnumTest {
public static void main(String args[]){
PaperSize ps=PaperSize.A4;
System.out.println(ps.getDim1());
System.out.println(ps.getDim2());
ps.setDim1(211);
System.out.println(ps.getDim1());
}
}
Enum (Contd.)
• The preceding code output will be:
210
297
211
Summary
• You have learnt that:
• Java defines the two streams, byte stream and character stream to read and
write data .
• Java byte streams are used to perform input and output of 8-bit bytes.
• Java character streams are used to perform input and output for 16-bit
Unicode.
• To perform the read and write operation, Java provides a set of classes packed
inside java.io package.
• Java provides a set classes inside the java.io package to perfrom I/O
operations.
• Serialization is a process in which current state of Object will be saved in
stream of bytes.
Summary
• Annotations are meta data that provide information about the code.
• Annotations are not a part of code.
• Annotations can be used to mark Java elements, such as package,
constructors, methods, fields, parameters and variables, within the code.
• Annotations allows the compiler and JVM to extract the program behavior
and generate the interdependent code when required.
• An annotation is prefixed with @ symbol.
• Java provided a set of built-in annotations.
• An enum type is a special data type that allows to create a set of constants.
• An enum can declare variables and define constructors and methods.

More Related Content

What's hot

16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queuesIntro C# Book
 
03 Java Language And OOP Part III
03 Java Language And OOP Part III03 Java Language And OOP Part III
03 Java Language And OOP Part IIIHari Christian
 
06 Java Language And OOP Part VI
06 Java Language And OOP Part VI06 Java Language And OOP Part VI
06 Java Language And OOP Part VIHari Christian
 
Java generics
Java genericsJava generics
Java genericsHosein Zare
 
Introduction to Haskell: 2011-04-13
Introduction to Haskell: 2011-04-13Introduction to Haskell: 2011-04-13
Introduction to Haskell: 2011-04-13Jay Coskey
 
Ios development
Ios developmentIos development
Ios developmentelnaqah
 
SQL Server Select Topics
SQL Server Select TopicsSQL Server Select Topics
SQL Server Select TopicsJay Coskey
 
04 Java Language And OOP Part IV
04 Java Language And OOP Part IV04 Java Language And OOP Part IV
04 Java Language And OOP Part IVHari Christian
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCOUM SAOKOSAL
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsRakesh Waghela
 
01 Java Language And OOP Part I LAB
01 Java Language And OOP Part I LAB01 Java Language And OOP Part I LAB
01 Java Language And OOP Part I LABHari Christian
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaSandesh Sharma
 
05 Java Language And OOP Part V
05 Java Language And OOP Part V05 Java Language And OOP Part V
05 Java Language And OOP Part VHari Christian
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOPSunil OS
 
java training faridabad
java training faridabadjava training faridabad
java training faridabadWoxa Technologies
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelRamrao Desai
 

What's hot (20)

16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
 
Class method
Class methodClass method
Class method
 
03 Java Language And OOP Part III
03 Java Language And OOP Part III03 Java Language And OOP Part III
03 Java Language And OOP Part III
 
06 Java Language And OOP Part VI
06 Java Language And OOP Part VI06 Java Language And OOP Part VI
06 Java Language And OOP Part VI
 
Java generics
Java genericsJava generics
Java generics
 
Introduction to Haskell: 2011-04-13
Introduction to Haskell: 2011-04-13Introduction to Haskell: 2011-04-13
Introduction to Haskell: 2011-04-13
 
Ios development
Ios developmentIos development
Ios development
 
Java Tutorials
Java Tutorials Java Tutorials
Java Tutorials
 
Core java Essentials
Core java EssentialsCore java Essentials
Core java Essentials
 
SQL Server Select Topics
SQL Server Select TopicsSQL Server Select Topics
SQL Server Select Topics
 
04 Java Language And OOP Part IV
04 Java Language And OOP Part IV04 Java Language And OOP Part IV
04 Java Language And OOP Part IV
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBC
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and Pitfalls
 
01 Java Language And OOP Part I LAB
01 Java Language And OOP Part I LAB01 Java Language And OOP Part I LAB
01 Java Language And OOP Part I LAB
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
 
05 Java Language And OOP Part V
05 Java Language And OOP Part V05 Java Language And OOP Part V
05 Java Language And OOP Part V
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
 

Viewers also liked (20)

Android - Day 2
Android - Day 2Android - Day 2
Android - Day 2
 
Agile Dev. I
Agile Dev. IAgile Dev. I
Agile Dev. I
 
MongoDB Session 1
MongoDB Session 1MongoDB Session 1
MongoDB Session 1
 
JSP Technology II
JSP Technology IIJSP Technology II
JSP Technology II
 
Hibernate III
Hibernate IIIHibernate III
Hibernate III
 
Identifing Listeners and Filters
Identifing Listeners and FiltersIdentifing Listeners and Filters
Identifing Listeners and Filters
 
Final Table of Content
Final Table of ContentFinal Table of Content
Final Table of Content
 
Working with Servlets
Working with ServletsWorking with Servlets
Working with Servlets
 
Agile Dev. II
Agile Dev. IIAgile Dev. II
Agile Dev. II
 
MongoDB Session 2
MongoDB Session 2MongoDB Session 2
MongoDB Session 2
 
Java Day-2
Java Day-2Java Day-2
Java Day-2
 
JSP Technology I
JSP Technology IJSP Technology I
JSP Technology I
 
RDBMS with MySQL
RDBMS with MySQLRDBMS with MySQL
RDBMS with MySQL
 
Spring Framework-II
Spring Framework-IISpring Framework-II
Spring Framework-II
 
Exploring Maven SVN GIT
Exploring Maven SVN GITExploring Maven SVN GIT
Exploring Maven SVN GIT
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Hibernate I
Hibernate IHibernate I
Hibernate I
 
Basic Hibernate Final
Basic Hibernate FinalBasic Hibernate Final
Basic Hibernate Final
 
Hibernate II
Hibernate IIHibernate II
Hibernate II
 
JDBC
JDBCJDBC
JDBC
 

Similar to Java Day-6

File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptxcherryreddygannu
 
Input/Output Exploring java.io
Input/Output Exploring java.ioInput/Output Exploring java.io
Input/Output Exploring java.ioNilaNila16
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streamsHamid Ghorbani
 
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 StreamsDon Bosco BSIT
 
Input output files in java
Input output files in javaInput output files in java
Input output files in javaKavitha713564
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdfSudhanshiBakre1
 
Computer science input and output BASICS.pptx
Computer science input and output BASICS.pptxComputer science input and output BASICS.pptx
Computer science input and output BASICS.pptxRathanMB
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streamsShahjahan Samoon
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfVithalReddy3
 
Oodp mod4
Oodp mod4Oodp mod4
Oodp mod4cs19club
 
UNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf NotesUNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf NotesSakkaravarthiS1
 
H U F F M A N Algorithm Class
H U F F M A N Algorithm ClassH U F F M A N Algorithm Class
H U F F M A N Algorithm ClassJade Danial
 
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.pptxDrYogeshDeshmukh1
 
Java Tutorial Lab 6
Java Tutorial Lab 6Java Tutorial Lab 6
Java Tutorial Lab 6Berk Soysal
 
5java Io
5java Io5java Io
5java IoAdil Jafri
 

Similar to Java Day-6 (20)

File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
 
Java I/O
Java I/OJava I/O
Java I/O
 
Java
JavaJava
Java
 
Input/Output Exploring java.io
Input/Output Exploring java.ioInput/Output Exploring java.io
Input/Output Exploring java.io
 
Unit IV Notes.docx
Unit IV Notes.docxUnit IV Notes.docx
Unit IV Notes.docx
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
CORE JAVA-1
CORE JAVA-1CORE JAVA-1
CORE JAVA-1
 
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
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
 
Computer science input and output BASICS.pptx
Computer science input and output BASICS.pptxComputer science input and output BASICS.pptx
Computer science input and output BASICS.pptx
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
 
Oodp mod4
Oodp mod4Oodp mod4
Oodp mod4
 
UNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf NotesUNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf Notes
 
H U F F M A N Algorithm Class
H U F F M A N Algorithm ClassH U F F M A N Algorithm Class
H U F F M A N Algorithm Class
 
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 Tutorial Lab 6
Java Tutorial Lab 6Java Tutorial Lab 6
Java Tutorial Lab 6
 
5java Io
5java Io5java Io
5java Io
 

More from People Strategists (12)

MongoDB Session 3
MongoDB Session 3MongoDB Session 3
MongoDB Session 3
 
Android - Day 1
Android - Day 1Android - Day 1
Android - Day 1
 
Overview of web services
Overview of web servicesOverview of web services
Overview of web services
 
Spring Framework - III
Spring Framework - IIISpring Framework - III
Spring Framework - III
 
Spring Framework -I
Spring Framework -ISpring Framework -I
Spring Framework -I
 
Overview of JEE Technology
Overview of JEE TechnologyOverview of JEE Technology
Overview of JEE Technology
 
XML Schemas
XML SchemasXML Schemas
XML Schemas
 
JSON and XML
JSON and XMLJSON and XML
JSON and XML
 
Ajax and Jquery
Ajax and JqueryAjax and Jquery
Ajax and Jquery
 
CSS
CSSCSS
CSS
 
HTML/HTML5
HTML/HTML5HTML/HTML5
HTML/HTML5
 
Java Day-3
Java Day-3Java Day-3
Java Day-3
 

Recently uploaded

FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
WhatsApp 9892124323 âś“Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 âś“Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 âś“Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 âś“Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 

Recently uploaded (20)

FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
WhatsApp 9892124323 âś“Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 âś“Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 âś“Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 âś“Call Girls In Kalyan ( Mumbai ) secure service
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 

Java Day-6

  • 1. © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 1
  • 4. Basic IO • Java provides a standard way of reading from and writing to files. • Java defines the two streams, byte stream and character stream to read and write data . • Java byte streams are used to perform input and output of 8-bit bytes. • Java character streams are used to perform input and output for 16- bit Unicode. • To perform the read and write operation, Java provides a set of classes packed inside java.io package.
  • 5. Basic IO • Java provides a set classes inside the java.io package to perfrom I/O operations. • The hierarchy of classes in java.io package: java.lang.Object java.io.InputStream java.io.BufferedInputStream java.io.OutputStream java.io.BufferedOutputStream java.io.Reader java.io.BufferedReader java.io.Writer java.io.BufferedWriter
  • 6. InputStream Class • The InputStream class is used for reading byte streams. • The hierarchy of InputStream class: java.io.InputStream java.io.FileInputStream java.io.FilterInputStream java.ioBufferedInputStream java.io.DataInputStream
  • 7. InputStream Class (Contd.) • The following table list the methods in InputStream class: Return Type Method Name Description int available() Returns an estimate of the number of bytes that can be read void close() Closes the input stream and releases any system resources associated with the stream. int read() Reads the next byte of data from the input stream. int read(byte[] b) Reads some number of bytes from the input stream and stores them into the buffer array b. int read(byte[] b, int off, int len) Reads up to len bytes of data from the input stream into an array of bytes. long skip(long n) Skips over and discards n bytes of data from this input stream.
  • 8. OutputStream Class • The OutputStream class is used for writing byte stream. • The hierarchy of OutputStream class: java.io.OutputStream java.io.FileOutputStream java.io.FilterOutputStream java.ioBufferedOutputStream java.io.DataOutputStream
  • 9. OutputStream Class (Contd.) • The following table list the methods in OutputStream class: Return Type Method Name Description void close() Closes the input stream and releases any system resources associated with the stream. int flush() Flushes this output stream and forces any buffered output bytes to be written out. int writ(byte[] b) Writes b.length bytes from the specified byte array to this output stream. int write(byte[] b, int off, int len) Writes len bytes from the specified byte array starting at offset off to this output stream. long Write(int b) Writes the specified byte to this output stream.
  • 10. Reader Class • The Reader class is used for reading character streams. • The hierarchy of Reader class: java.io.Reader java.io.InputStreamReader java.io.FileReader java.ioBufferedReader
  • 11. Reader Class (Contd.) • The following table list the methods in Reader class: Return Type Method Name Description void close() Closes the input stream and releases any system resources associated with the stream. int read() Reads a single character. int read(char[] b) Reads characters into an array. int read(char[] b, int off, int len) Reads characters into a portion of an array. int read(CharBuffer target) Attempts to read characters into the specified character buffer. long skip(long n) Skips over and discards n bytes of data from this input stream.
  • 12. Writer Class • The Writer class is used for writing character streams. • The hierarchy of Writer class: java.io.Writer java.io.InputStreamWriter java.io.FileWriter java.io.BufferedWriter Java.io.PrintWriter
  • 13. Writer Class (Contd.) • The following table list the methods in Writer class: Return Type Method Name Description close close() Closes the input stream and releases any system resources associated with the stream. int flush() Flushes this output stream and forces any buffered output bytes to be written out. int writ(char[] b) Writes an array of characters. int write(char[] b, int off, int len) Writes a portion of an array of characters. long Write(int b) Writes a single character. void write(String str) Writes a string. void write(String str, int off, int len) Writes a portion of a string.
  • 14. File Class • The File class is used to access files, file attributes, and file systems. • The constructors in File class: • File(String pathname):Creates a new File instance by converting the given pathname string into an abstract pathname. • File(String parent, String child) :Creates a new File instance from a parent pathname string and a child pathname string.
  • 15. File Class (Contd.) • The following table list the methods in File class: Return Type Method Name Description boolean createNewFile() Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. boolean delete() Deletes the file or directory denoted by this abstract pathname. boolean exists() Tests whether the file or directory denoted by this abstract pathname exists. String getName() Returns the name of the file or directory denoted by this abstract pathname. boolean isFile() Tests whether the file denoted by this abstract pathname is a normal file. boolean isDirectory() Tests whether the file denoted by this abstract pathname is a directory. long length() Returns the length of the file denoted by this abstract pathname.
  • 16. File Class (Contd.) • The following table list the methods in File class: Return Type Method Name Description String[] list() Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname. boolean mkdir() Creates the directory named by this abstract pathname. boolean renameTo(File dest) Renames the file denoted by this abstract pathname.
  • 17. File Class (Contd.) • An example code to work with File class: import java.io.*; public class FileClassDemo { public static void main(String args[])throws IOException{ File f1=new File("TestFolder"); File f2=new File("TestFile.txt"); File f3=new File("D:FileTest.txt"); File f4=new File("NewFileTest.txt"); f3.createNewFile();
  • 19. Read and Write Operations • An example to read String from console and writing back to console using the InputStreamReader and BufferedReader classes: import java.io.*; class ConsoleIOStringDemo { public static void main(String[] args) throws IOException { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader input = new BufferedReader(isr); String name,line; System.out.println("Enter your name:"); name=input.readLine(); System.out.println("Hi!!!!!!!!!!!!!!!!!!!!!"+name); } }
  • 20. Read and Write Operations (Contd.) • An example read data from the console until the String quit is entered: import java.io.*; class ConsoleIOStringDemo { public static void main(String[] args) throws IOException { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader input = new BufferedReader(isr); String line; while ((line = input.readLine()) != null) { if(line.equals("quit")){ System.exit(1); } else{ System.out.println(line); } } } }
  • 21. Read and Write Operations (Contd.) • An example to read data from file and print to the console using FileInputStream class: import java.io.*; public class FileInputStreamDemo { public static void main(String args[])throws IOException{ try(FileInputStream fis = new FileInputStream("TestFile.txt");){ int i,j=0; while((i=fis.read())!=-1) { if((char)i ==' ') { j++;
  • 22. Read and Write Operations (Contd.) System.out.println(); } else { System.out.print((char)i); } } } } }
  • 23. Read and Write Operations (Contd.) • An example to read data from console and write to a file using BufferedReader and FileWriter classes: import java.io.*; public class ReadWriteDemo { public static void main(String args[]) throws IOException { String consoleData; try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); FileWriter fw = new FileWriter("FileTest.txt");) {
  • 24. Read and Write Operations (Contd.) while ((consoleData = br.readLine()) != null) { fw.write(consoleData); fw.flush(); } } catch (IOException e) { e.printStackTrace(); } } }
  • 25. Read and Write Operations (Contd.) • An example to read data from file and print to the console using FileReader and BufferedReader classes: import java.io.*; class FileReaderDemo { public static void main(String args[]) throws Exception { FileReader fr = new FileReader("TestFile.txt"); BufferedReader br = new BufferedReader(fr); String s; while((s = br.readLine()) != null) { System.out.println(s); } fr.close(); } }
  • 26. Read and Write Operations (Contd.) • An example to read file and write into another file using the FileInputStream and BufferedWriter classes. import java.io.*; public class ReadWriteDemo { public static void main(String st[]) throws Exception { int i; FileInputStream fis = new FileInputStream("TestFile.txt"); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("FOSFile.Txt"))); while ((i = fis.read()) != -1) { bw.flush(); bw.write(i); } } }
  • 27. Serialization • Serialization is a process in which current state of Object will be saved in stream of bytes. • Serialization is used when data needs to be sent over network or stored in files. • Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object. • The readObject() method is used to read an object. • The writeObject() method is used write an object
  • 28. Serialization (Contd.) • An example to implement serialization: import java.io.Serializable; public class Employee implements Serializable{ int employeeId; String employeeName; String department; public int getEmployeeId() { return employeeId; } public void setEmployeeId(int employeeId) { this.employeeId = employeeId; }
  • 29. Serialization (Contd.) public String getEmployeeName() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } }
  • 30. Serialization (Contd.) import java.io.*; public class SerializeMain { public static void main(String[] args) { Employee emp = new Employee(); emp.setEmployeeId(101); emp.setEmployeeName(“Raj"); emp.setDepartment("CS");
  • 31. Serialization (Contd.) try { FileOutputStream fileOut = new FileOutputStream("d:employee.txt"); ObjectOutputStream outStream = new ObjectOutputStream(fileOut); outStream.writeObject(emp); outStream.close(); fileOut.close(); }catch(IOException i) { i.printStackTrace(); } } }
  • 32. Serialization (Contd.) import java.io.*; public class DeserializeMain { public static void main(String[] args) { Employee emp = null; try { FileInputStream fileIn =new FileInputStream("D:employee.txt"); ObjectInputStream in = new ObjectInputStream(fileIn); emp = (Employee) in.readObject(); in.close(); fileIn.close(); }
  • 33. Serialization (Contd.) catch(IOException i) { i.printStackTrace(); return; }catch(ClassNotFoundException c) { System.out.println("Employee class not found"); c.printStackTrace(); return; } System.out.println("Deserialized Employee..."); System.out.println("Emp id: " + emp.getEmployeeId()); System.out.println("Name: " + emp.getEmployeeName()); System.out.println("Department: " + emp.getDepartment()); } }
  • 35. Annotations Basics • Annotations are meta data that provide information about the code. • Annotations are not a part of code. • Annotations can be used to mark Java elements, such as package, constructors, methods, fields, parameters and variables, within the code. • Annotations allows the compiler and JVM to extract the program behavior and generate the interdependent code when required. • An annotation is prefixed with @ symbol.
  • 36. Built-in Java Annotations • Java provides a set of built-in annotations. • These built-in annotations can be categorized in as: • Annotations used by the Java language • Annotations applied to other annotation • The annotations used by the Java language are defined inside the java.lang package. • The annotations applied to other annotation are defined inside the java.lang.annotation package. These annotations are also called as meta-annotation. • The meta-annotations are mostly used with user-defined annotations.
  • 37. Built-in Java Annotations (Contd.) • The commonly used annotation by Java language are: • @Override • @SuppressWarnings • The commonly used annotations applied to other annotation are: • @Retention • @Target • @Inherited • @Documented
  • 38. Built-in Java Annotations (Contd.) • @Override: Annotation is used to inform the compiler that the method using the annotation is an overridden method. • Consider the following code snippet: class Base{ void display(){ } } class Sub extends Base{ @Override void display(){ } }
  • 39. Built-in Java Annotations (Contd.) • In the preceding code, if the method using the annotation is not a overridden method then a compilation error will be raised. • @SuppressWarnings: Annotation is used to inform the compiler to suppress warnings raised by the method using the annotation. • Consider the following code: void getData()throws IOException{ DataInputStream dis=new DataInputStream(System.in); String s=dis.readLine(); }
  • 40. Built-in Java Annotations (Contd.) • The preceding code will raise a warning because the readLine() method is a deprecated method. This warning can be suppressed by adding the following statement before the method definition: @SuppressWarnings("deprecation") • Here, deprecation is the warning category. • The @SuppressWarnings annotation can accept the warning categories, deprecation and unchecked. • To suppress multiple categories of warnings the following statement is used: @SuppressWarnings({"unchecked", "deprecation"})
  • 41. Built-in Java Annotations (Contd.) • @Retention: Annotation is used to specify how the marked annotation is stored. This annotation accepts one of the following retention policy as argument: • RetentionPolicy.SOURCE – The marked annotation is retained only in the source level and is ignored by the compiler. • RetentionPolicy.CLASS – The marked annotation is retained by the compiler at compile time, but is ignored by the JVM. • RetentionPolicy.RUNTIME – The marked annotation is retained by the JVM so it can be used by the runtime environment.
  • 42. Built-in Java Annotations (Contd.) • @Documented :Annotation is used to indicates that the annotation should be documented. • @Target: Annotation is used to restrict the usage of the annotation on certain Java elements. A target annotation can accept one of the following element types as its argument: • ElementType.ANNOTATION_TYPE - Can be applied to an annotation type. • ElementType.CONSTRUCTOR - Can be applied to a constructor. • ElementType.FIELD - Can be applied to a field or property. • ElementType.LOCAL_VARIABLE - Can be applied to a local variable. • ElementType.METHOD - Can be applied to a method-level annotation. • ElementType.PACKAGE - Can be applied to a package declaration. • ElementType.PARAMETER - Can be applied to the parameters of a method. • ElementType.TYPE - Can be applied to any element of a class.
  • 43. Built-in Java Annotations (Contd.) • @Inherited: Annotation is used to indicate that the annotation type is automatically inherited. When the user queries the annotation type and the class has no annotation the defined type, then the superclass is queried for the annotation type. The @Inherited annotation is applied only to class declarations.
  • 44. User-defined Annotations • Java allows to create a user-defined annotation. • The @interface element is used to declare an annotation. • An example to create a user-defined annotation: public abstract @interface DescAnnotation { String description(); } • An example to use the user defined annotation: @DescAnnotation(description="AnnotationDemo Class") public class AnnotationsDemo { @DescAnnotation(description="Display method") void display(){ }
  • 45. User-defined Annotations (Contd.) • The annotations can have any number of fields. • An example to create a user-defined annotation with multiple fields: public abstract @interface DescAnnotation { String description(); int version(); } • The class elements using the preceding annotation should define both fields else an compilation error will be raised.
  • 46. User-defined Annotations (Contd.) • An example to create a user-defined annotation with default field value: public abstract @interface DescAnnotation { String description(); int version() default 1; } • The class elements using the preceding annotation can omit the definition of version field.
  • 47. User-defined Annotations (Contd.) • An example to create a user-defined annotation with @Retention: import java.lang.annotation.*; @Retention(RetentionPolicy.CLASS) public abstract @interface DescAnnotation { String description(); int version() default 1; } • The DescAnnotation annotation will be embedded into the generated class file.
  • 48. User-defined Annotations (Contd.) • An example to create a user-defined annotation with @Documented: import java.lang.annotation.*; @Documented public abstract @interface DescAnnotation { String description(); int version() default 1; } • The DescAnnotation annotation will be included into Java documents generated by Java document generator tools.
  • 49. User-defined Annotations (Contd.) • An example to create a user-defined annotation with @Target: import java.lang.annotation.*; @Target({ ElementType.FIELD, ElementType.METHOD}) public abstract @interface DescAnnotation { String description(); int version() default 1; } • If the preceding annotation is used with elements other than method or field, a compilation error will be raised.
  • 50. User-defined Annotations (Contd.) • An example to create a user-defined annotation with @@Inherited: import java.lang.annotation.*; @Inherited public abstract @interface DescAnnotation { String description(); int version() default 1; } • If the preceding annotation is applied to base class then this annotation is also available to the sub class.
  • 51. Enum • An enum type is a special data type that allows to create a set of constants. • An enum is defined using the enum keyword. • An enum is created when all the possible values of a data set is know. • An example to create a enum: public enum PaperSize { A0,A1,A2,A3,A4,A5,A6,A7,A8 } • You can create a variable of enum type as shown in the following code snippet: PaperSize ps=PaperSize.A4;
  • 52. Enum (Contd.) • An enum can be defined inside or outside the class. • The enum defined outside class can use only public access modifier. However, the enum declared inside the class can use all the four access modifier. • An enum can declare variables and define constructors and methods. • An example to define enum with variables, constructor, and methods: public enum PaperSize { A0(841,1189),A1(594,841),A2(420,594),A3( 297,420),A4(210,297),A5(148,210),A6(105,148),A7(74,105 ),A8(52,74);
  • 53. Enum (Contd.) int dim1,dim2; public int getDim1() { return dim1; } public void setDim1(int dim1) { this.dim1 = dim1; } public int getDim2() { return dim2; } public void setDim2(int dim2) { this.dim2 = dim2; } PaperSize(int dim1,int dim2){ this.dim1=dim1; this.dim2=dim2; } }
  • 54. Enum (Contd.) public class EnumTest { public static void main(String args[]){ PaperSize ps=PaperSize.A4; System.out.println(ps.getDim1()); System.out.println(ps.getDim2()); ps.setDim1(211); System.out.println(ps.getDim1()); } }
  • 55. Enum (Contd.) • The preceding code output will be: 210 297 211
  • 56. Summary • You have learnt that: • Java defines the two streams, byte stream and character stream to read and write data . • Java byte streams are used to perform input and output of 8-bit bytes. • Java character streams are used to perform input and output for 16-bit Unicode. • To perform the read and write operation, Java provides a set of classes packed inside java.io package. • Java provides a set classes inside the java.io package to perfrom I/O operations. • Serialization is a process in which current state of Object will be saved in stream of bytes.
  • 57. Summary • Annotations are meta data that provide information about the code. • Annotations are not a part of code. • Annotations can be used to mark Java elements, such as package, constructors, methods, fields, parameters and variables, within the code. • Annotations allows the compiler and JVM to extract the program behavior and generate the interdependent code when required. • An annotation is prefixed with @ symbol. • Java provided a set of built-in annotations. • An enum type is a special data type that allows to create a set of constants. • An enum can declare variables and define constructors and methods.