Java Day-6

Preview:

Citation preview

© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com

1

Day 6Input/Output Operations

Annotation BasicsEnum

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/Ooperations.

• 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 canbe read

void close() Closes the input stream and releases any systemresources 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 streamand stores them into the buffer array b.

int read(byte[] b, int off, intlen)

Reads up to len bytes of data from the input streaminto an array of bytes.

long skip(long n) Skips over and discards n bytes of data from thisinput 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 systemresources associated with the stream.

int flush() Flushes this output stream and forces anybuffered output bytes to be written out.

int writ(byte[] b) Writes b.length bytes from the specified bytearray to this output stream.

int write(byte[] b, int off,int len)

Writes len bytes from the specified byte arraystarting 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 systemresources 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 specifiedcharacter buffer.

long skip(long n) Skips over and discards n bytes of data from thisinput 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 systemresources associated with the stream.

int flush() Flushes this output stream and forces anybuffered 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 givenpathname string into an abstract pathname.

• File(String parent, String child) :Creates a new File instance from a parentpathname 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 abstractpathname 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 abstractpathname exists.

String getName() Returns the name of the file or directory denoted by this abstractpathname.

boolean isFile() Tests whether the file denoted by this abstract pathname is anormal file.

boolean isDirectory() Tests whether the file denoted by this abstract pathname is adirectory.

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 thedirectory 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 consoleusing 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 usingFileInputStream 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 usingBufferedReader and FileWriter classes:import java.io.*;public class ReadWriteDemo {

public static void main(String args[]) throwsIOException {

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 usingFileReader 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 theFileInputStream 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 savedin stream of bytes.

• Serialization is used when data needs to be sent over network orstored in files.

• Classes ObjectInputStream and ObjectOutputStream are high-levelstreams that contain the methods for serializing and deserializing anobject.

• 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 =newFileInputStream("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 thecode.

• Annotations allows the compiler and JVM to extract the programbehavior 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 thejava.lang package.

• The annotations applied to other annotation are defined inside thejava.lang.annotation package. These annotations are also called asmeta-annotation.

• The meta-annotations are mostly used with user-definedannotations.

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 themethod 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 overriddenmethod then a compilation error will be raised.

• @SuppressWarnings: Annotation is used to inform the compiler tosuppress warnings raised by the method using the annotation.

• Consider the following code:void getData()throws IOException{

DataInputStream dis=newDataInputStream(System.in);

String s=dis.readLine();

}

Built-in Java Annotations (Contd.)

• The preceding code will raise a warning because the readLine() method is adeprecated method. This warning can be suppressed by adding the followingstatement 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 markedannotation is stored. This annotation accepts one of the followingretention policy as argument:

• RetentionPolicy.SOURCE – The marked annotation is retained only in thesource level and is ignored by the compiler.

• RetentionPolicy.CLASS – The marked annotation is retained by the compiler atcompile time, but is ignored by the JVM.

• RetentionPolicy.RUNTIME – The marked annotation is retained by the JVM soit can be used by the runtime environment.

Built-in Java Annotations (Contd.)

• @Documented :Annotation is used to indicates that the annotation shouldbe documented.

• @Target: Annotation is used to restrict the usage of the annotation oncertain Java elements. A target annotation can accept one of the followingelement 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 annotationtype is automatically inherited. When the user queries theannotation 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 defineboth fields else an compilation error will be raised.

User-defined Annotations (Contd.)

• An example to create a user-defined annotation with default fieldvalue:public abstract @interface DescAnnotation {

String description();int version() default 1;

}

• The class elements using the preceding annotation can omit thedefinition 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 generatedclass file.

User-defined Annotations (Contd.)

• An example to create a user-defined annotation with @Documented:import java.lang.annotation.*;@Documentedpublic abstract @interface DescAnnotation {

String description();int version() default 1;

}

• The DescAnnotation annotation will be included into Java documentsgenerated 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 methodor 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.*;@Inheritedpublic abstract @interface DescAnnotation {

String description();int version() default 1;

}

• If the preceding annotation is applied to base class then thisannotation 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 codesnippet: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 fouraccess 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:210297211

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.