0% found this document useful (0 votes)
1 views36 pages

Java Unit II Part II

The document outlines the Java Programming curriculum for II B.Tech II-Semester at Jyothishmathi Institute of Technology and Science, focusing on key topics such as packages, interfaces, and stream-based I/O operations. It explains the concepts of byte and character streams, including their classes and methods for reading and writing data. Additionally, it provides examples of using BufferedInputStream, BufferedOutputStream, BufferedReader, and FileWriter for console and file I/O operations.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views36 pages

Java Unit II Part II

The document outlines the Java Programming curriculum for II B.Tech II-Semester at Jyothishmathi Institute of Technology and Science, focusing on key topics such as packages, interfaces, and stream-based I/O operations. It explains the concepts of byte and character streams, including their classes and methods for reading and writing data. Additionally, it provides examples of using BufferedInputStream, BufferedOutputStream, BufferedReader, and FileWriter for console and file I/O operations.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND

SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22

II [Link] II- Semester


CS405PC
Java Programming (R18) 2021-22

UNIT-II PART-II

Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 1


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22

UNIT-II

Packages- Defining a Package, CLASSPATH, Access protection, importing packages.


Interfaces- defining an interface, implementing interfaces, Nested interfaces, applying
interfaces, variables in interfaces and extending interfaces.
Stream based I/O ([Link]) – The Stream classes-Byte streams and Character streams,
Reading console Input and Writing Console Output, File class, Reading and writing Files,
Random access file operations, The Console class, Serialization, Enumerations, auto boxing,
generics.

Stream in java

In java, the IO operations are performed using the concept of streams. Generally, a stream
means a continuous flow of data. In java, a stream is a logical container of data that allows
us to read from and write to it. A stream can be linked to a data source, or data destinations,
like a console, file or network connection by java IO system. The stream-based IO
operations are faster than normal IO operations.

The Stream is defined in the [Link] package.

To understand the functionality of java streams, look at the following picture.

In java, the stream-based IO operations are performed using two separate streams input
stream and output stream. The input stream is used for input operations, and the output
stream is used for output operations. The java stream is composed of bytes.

Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 2


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22

In Java, every program creates 3 streams automatically, and these streams are attached to the
console.
✔ [Link]: standard output stream for console output operations.
✔ [Link]: standard input stream for console input operations.
✔ [Link]: standard error stream for console error output operations.

The Java streams support many different kinds of data, including simple bytes, primitive
data types, localized characters, and objects.

Java provides two types of streams, and they are as follows.

✔ Byte Stream
✔ Character Stream

The following picture shows how streams are categorized, and various built-in classes used
by the java IO system.

Both character and byte streams essentially provides a convenient and efficient way to
handle data streams in Java.

Byte Stream in java

Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 3


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
In java, the byte stream is an 8 bits carrier. The byte stream in java allows us to transmit 8
bits of data.
In Java 1.0 version all IO operations were byte oriented, there was no other stream
(character stream).
The java byte stream is defined by two abstract classes, InputStream and OutputStream.
The InputStream class used for byte stream based input operations, and the OutputStream
class used for byte stream based output operations.
The InputStream and OutputStream classes have several concreate classes to perform
various IO operations based on the byte stream.

The following picture shows the classes used for byte stream operations.

InputStream class
The InputStream class has defined as an abstract class, and it has the following methods
which have implemented by its concrete classes.

[Link]. Method with Description

int available()
1
It returns the number of bytes that can be read from the input stream.

int read()
2
It reads the next byte from the input stream.

Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 4


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link]. Method with Description

int read(byte[] b)
3
It reads a chunk of bytes from the input stream and store them in its byte array, b.

void close()
4 It closes the input stream and also frees any resources connected with this input
stream.

OutputStream class
The OutputStream class has defined as an abstract class, and it has the following methods
which have implemented by its concrete classes.

[Link]. Method with Description

void write(int n)
1
It writes byte(contained in an int) to the output stream.

void write(byte[] b)
2
It writes a whole byte array(b) to the output stream.

void flush()
3
It flushes the output steam by forcing out buffered bytes to be written out.

void close()
4 It closes the output stream and also frees any resources connected with this output
stream.

Reading data using BufferedInputStream


We can use the BufferedInputStream class to read data from the console. The
BufferedInputStream class use a method read( ) to read a value from the console, or file, or
socket.
Let's look at an example code to illustrate reading data using BufferedInputStream.

Example: Reading from console


import [Link].*;

public class ReadingDemo {

public static void main(String[] args) throws IOException {

BufferedInputStream read = new BufferedInputStream([Link]);

Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 5


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22

try {
[Link]("Enter any character: ");
char c = (char)[Link]();
[Link]("You have entered '" + c + "'");
}
catch(Exception e) {
[Link](e);
}
finally {
[Link]();
}
}
}
Output:
Enter any character: A
You have entered 'A'

Example:2 Reading from a file


import [Link].*;

public class ReadingFileDemo {

public static void main(String[] args) throws IOException {

FileInputStream fileInputStream = new FileInputStream(new


File("C:\\javaclass\\[Link]"));
BufferedInputStream input = new BufferedInputStream(fileInputStream);
try {
char c = (char)[Link]();
[Link]("Data read from a file - '" + c + "'");
}
catch(Exception e) {
[Link](e);
}
finally {
[Link]();
}
}
}
Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 6
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Output:
C:\\javaclass\\[Link] contains pathway for quality improvement
C:\javaclass>java ReadingFileDemo
Data read from a file - 'p'

Writing data using BufferedOutputStream

We can use the BufferedOutputStream class to write data into the console, file, socket. The
BufferedOutputStream class use a method write( ) to write data.

Example code to illustrate writing data into a file using BufferedOutputStream.

Example:
//Example - Writing data into a file
import [Link].*;

public class WritingDemo {

public static void main(String[] args) throws IOException {

String data = "Jyothishmathi II year Java Programmers";


BufferedOutputStream out = null;
try {
FileOutputStream fileOutputStream = new FileOutputStream(new
File("C:\\javaclass\\[Link]"));
out = new BufferedOutputStream(fileOutputStream);

[Link]([Link]());
[Link]("Writing data into a file is success!");

}
catch(Exception e) {
[Link](e);
}
finally {
[Link]();
}
}
}
Output:
C:\javaclass>java WritingDemo

Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 7


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Writing data into a file is success!
Jyothishmathi II year Java Programmers content was updated in [Link]

Character Stream in java

In java, when the IO stream manages 16-bit Unicode characters, it is called a character
stream. The unicode set is basically a type of character set where each character corresponds
to a specific numeric value within the given character set, and every programming language
has a character set.

In java, the character stream is a 16 bits carrier. The character stream in java allows us to
transmit 16 bits of data.

The character stream was introduced in Java 1.1 version.

The java character stream is defined by two abstract classes, Reader and Writer. The
Reader class used for character stream based input operations, and the Writer class used for
character stream based output operations.

The Reader and Writer classes have several existing classes to perform various IO
operations based on the character stream.

The following picture shows the classes used for character stream operations.

Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 8


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22

Reader class
The Reader class has defined as an abstract class, and it has the following methods which
have implemented by its concrete classes.
[Link]. Method with Description

1 int read()
It reads the next character from the input stream.

2 int read(char[] cbuffer)


It reads a chunk of characters from the input stream and stores them in its byte array,
cbuffer.

3 int read(char[] cbuf, int off, int len)


It reads characters into a portion of an array.

4 int read(CharBuffer target)


It reads characters into the specified character buffer.

5 String readLine()
It reads a line of text. A line is considered to be terminated by any one of a line feed
('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

6 boolean ready()
It tells whether the stream is ready to be read.

7 void close()
It closes the input stream and also frees any resources connected with this input
stream.
Writer class
The Writer class has defined as an abstract class, and it has the following methods which
have implemented by its concrete classes.

[Link]. Method with Description

1 void flush()
It flushes the output steam by forcing out buffered bytes to be written out.

2 void write(char[] cbuf)


It writes a whole array(cbuf) to the output stream.

3 void write(char[] cbuf, int off, int len)


It writes a portion of an array of characters.

Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 9


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link]. Method with Description

4 void write(int c)
It writes single character.

5 void write(String str)


It writes a string.

6 void write(String str, int off, int len)


It writes a portion of a string.

7 Writer append(char c)
It appends the specified character to the writer.

8 Writer append(CharSequence csq)


It appends the specified character sequence to the writer

9 Writer append(CharSequence csq, int start, int end)


It appends a subsequence of the specified character sequence to the writer.

10 void close()
It closes the output stream and also frees any resources connected with this output
stream.

Reading data using BufferedReader

We can use the BufferedReader class to read data from the console. The
BufferedInputStream class needs InputStreamReaderclass. The BufferedReader use a
method read( ) to read a value from the console, or file, or socket.

Let's look at an example code to illustrate reading data using BufferedReader.

//Example 1 Reading data using BufferedReader


import [Link].*;

public class ReadingBufferDemo {

public static void main(String[] args) throws IOException {

InputStreamReader isr = new InputStreamReader([Link]);


BufferedReader in = new BufferedReader(isr);

String name = "";

Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 10


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link]("Please enter your name: ");

name = [Link]();

[Link]("Hai Java Programmer, " + name + "!");


}
}
Output:
Please enter your name: VARUNJOEL
Hai Java Programmer, VARUNJOEL!

Writing data using FileWriter


We can use the FileWriter class to write data into the file. The FileWriter class use a method
write( ) to write data.

Example code to illustrate writing data into a file using FileWriter.

//Example - Writing data into a file


import [Link].*;

public class WritingDemoWtr {

public static void main(String[] args) throws IOException {

Writer out = new FileWriter("C:\\javaclass\\[Link]");

String msg = "Hai Java Programmer,How are you..";

try {
[Link](msg);
[Link]("Writing done!!!");
}
catch(Exception e) {
[Link](e);
}
finally {
[Link]();
}
}
}
Output:
Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 11
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Writing done!!!

Console IO Operations in Java


Reading console input in java
In java, there are three ways to read console input. Using the 3 following ways, we can read
input data from the console.

● Using BufferedReader class


● Using Scanner class
● Using Console class
Let's explore the each method to read data with example.

1. Reading console input using BufferedReader class in java

Reading input data using the BufferedReader class is the traditional technique. This way of
the reading method is used by wrapping the [Link] (standard input stream) in
an InputStreamReader which is wrapped in a BufferedReader, we can read input from
the console.
The BufferedReader class has defined in the [Link] package.

Example:
//Reading console input using BufferedReader class in java

import [Link].*;

public class ReadingConsoleDemoB {

public static void main(String[] args) throws IOException {

BufferedReader in = new BufferedReader(new


InputStreamReader([Link]));

String name = "";

try {
[Link]("Please enter your name : ");
name = [Link]();
[Link]("Hello, " + name + "!");
}
catch(Exception e) {
[Link](e);
}
finally {
Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 12
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link]();
}
}
}
Output:

Please enter your name : varunjoel


Hello, varunjoel!

2. Reading console input using Scanner class in java

Reading input data using the Scanner class is the most commonly used method. This way
of the reading method is used by wrapping the [Link] (standard input stream) which is
wrapped in a Scanner, we can read input from the console.

The Scanner class has defined in the [Link] package.

Consider the following example code to understand how to read console input using
Scanner class.

Example:
import [Link];

public class ReadingScannerDemo {

public static void main(String[] args) {


Scanner in = new Scanner([Link]);
String name = "";
[Link]("Please enter your name : ");
name = [Link]();
[Link]("Hello, " + name + "!");

}
}
Output:

Please enter your name : varunjoel


Hello, varunjoel!

3. Reading console input using Console class in java

Reading input data using the Console class is the most commonly used method. This class
was introduced in Java 1.6 version.
The Console class has defined in the [Link] package.

Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 13


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Consider the following example code to understand how to read console input using
Console class.
Example:
import [Link].*;

public class ReadingConsoleDemo1 {


public static void main(String[] args) {
String name;
Console con = [Link]();

if(con != null) {
name = [Link]("Please enter your name : ");
[Link]("Hello, " + name + "!!");
}
else {
[Link]("Console not available.");
}
}
}
Output:

Please enter your name : varunjoel


Hello, varunjoel!

Writing console output in java


In java, there are two methods to write console output. Using the 2 following methods, we
can write output data to the console.

● Using print() and println() methods


● Using write() method
Let's explore the each method to write data with example.

1. Writing console output using print() and println() methods

The PrintStream is a bult-in class that provides two methods print() and println() to write
console output. The print() and println() methods are the most widely used methods for
console output.

Both print() and println() methods are used with [Link] stream.

The print() method writes console output in the same line. This method can be used with
console output only.
Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 14
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
The println() method writes console output in a separate line (new line). This method can be
used with console and also with other output sources.
Let's look at the following code to illustrate print() and println() methods.
Example:
public class WritingPrintDemo {

public static void main(String[] args) {

int[] list = new int[5];

for(int i = 0; i < 5; i++)


list[i] = i*10;

for(int i:list)
[Link](i); //prints in same line

[Link]("");
for(int i:list)
[Link](i); //Prints in separate lines

}
}
Output:
010203040 //prints in same line
0 //Prints in separate lines
10
20
30
40

2. Writing console output using write() method

Alternatively, the PrintStream class provides a method write() to write console output.

The write() method take integer as argument, and writes its ASCII equalent character on to
the console, it also accept escape sequences.

Let's look at the following code to illustrate write() method.


Example:
public class WritingPrintDemo1 {

Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 15


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
public static void main(String[] args) {

int[] list = new int[26];

for(int i = 0; i < 26; i++) {


list[i] = i + 65;
}

for(int i:list) {
[Link](i);
[Link]('\n');
}
}
}
Output:
A to Z //print A,B,C …to Z (vertical)

File class in Java

The File is a built-in class in Java. In java, the File class has been defined in the [Link]
package. The File class represents a reference to a file or directory. The File class has
various methods to perform operations like creating a file or directory, reading from a file,
updating file content, and deleting a file or directory.

The File class in java has the following constructors.

[Link]. Constructor with Description

1 File(String pathname)
It creates a new File instance by converting the given pathname string into an
abstract pathname. If the given string is the empty string, then the result is the empty
abstract pathname.

2 File(String parent, String child)


It Creates a new File instance from a parent abstract pathname and a child pathname
string. If parent is null then the new File instance is created as if by invoking the
single-argument File constructor on the given child pathname string.

3 File(File parent, String child)

Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 16


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link]. Constructor with Description

It creates a new File instance from a parent abstract pathname and a child pathname
string. If parent is null then the new File instance is created as if by invoking the
single-argument File constructor on the given child pathname string.

4 File(URI uri)
It creates a new File instance by converting the given file: URI into an abstract
pathname.

The File class in java has the following methods.


[Link]. Methods with Description

1 String getName()
It returns the name of the file or directory that referenced by the current File object.

2 String getParent()
It returns the pathname of the pathname's parent, or null if the pathname does not
name a parent directory.

3 String getPath()
It returns the path of curent File.

4 File getParentFile()
It returns the path of the current file's parent; or null if it does not exist.

5 String getAbsolutePath()
It returns the current file or directory path from the root.

6 boolean isAbsolute()
It returns true if the current file is absolute, false otherwise.

7 boolean isDirectory()
It returns true, if the current file is a directory; otherwise returns false.

8 boolean isFile()
It returns true, if the current file is a file; otherwise returns false.

9 boolean exists()
It returns true if the current file or directory exist; otherwise returns false.

Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 17


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link]. Methods with Description

10 boolean canRead()
It returns true if and only if the file specified exists and can be read by the
application; false otherwise.

11 boolean canWrite()
It returns true if and only if the file specified exists and the application is allowed to
write to the file; false otherwise.

12 long length()
It returns the length of the current file.

13 long lastModified()
It returns the time that specifies the file was last modified.

14 boolean createNewFile()
It returns true if the named file does not exist and was successfully created; false if
the named file already exists.

15 boolean delete()
It deletes the file or directory. And returns true if and only if the file or directory is
successfully deleted; false otherwise.

16 void deleteOnExit()
It sends a requests that the file or directory needs be deleted when the virtual
machine terminates.

17 boolean mkdir()
It returns true if and only if the directory was created; false otherwise.

18 boolean mkdirs()
It returns true if and only if the directory was created, along with all necessary
parent directories; false otherwise.

19 boolean renameTo(File dest)


It renames the current file. And returns true if and only if the renaming succeeded;
false otherwise.

20 boolean setLastModified(long time)


It sets the last-modified time of the file or directory. And returns true if and only if
the operation succeeded; false otherwise.

Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 18


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link]. Methods with Description

21 boolean setReadOnly()
It sets the file permission to only read operations; Returns true if and only if the
operation succeeded; false otherwise.

22 String[] list()
It returns an array of strings containing names of all the files and directories in the
current directory.

23 String[] list(FilenameFilter filter)


It returns an array of strings containing names of all the files and directories in the
current directory that satisfy the specified filter.

24 File[] listFiles()
It returns an array of file references containing names of all the files and directories
in the current directory.

25 File[] listFiles(FileFilter filter)


It returns an array of file references containing names of all the files and directories
in the current directory that satisfy the specified filter.

26 boolean equals(Object obj)


It returns true if and only if the argument is not null and is an abstract pathname that
denotes the same file or directory as this abstract pathname.

27 int compareTo(File pathname)


It Compares two abstract pathnames lexicographically. It returns zero if the
argument is equal to this abstract pathname, a value less than zero if this abstract
pathname is lexicographically less than the argument, or a value greater than zero if
this abstract pathname is lexicographically greater than the argument.

28 int compareTo(File pathname)


Compares this abstract pathname to another object. Returns zero if the argument is
equal to this abstract pathname, a value less than zero if this abstract pathname is
lexicographically less than the argument, or a value greater than zero if this abstract
pathname is lexicographically greater than the argument.

The following source code to illustrate file operations.


Example:
import [Link].*;
public class FileClassTest {

Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 19


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22

public static void main(String args[]) {


File f = new File("C:\\javaclass\\[Link]");

[Link]("Executable File : " + [Link]());


[Link]("Name of the file : " + [Link]());
[Link]("Path of the file : " + [Link]());
[Link]("Parent name : " + [Link]());
[Link]("Write mode : " + [Link]());
[Link]("Read mode : " + [Link]());

}
Output:
C:\javaclass>java FileClassTest
Executable File : false
Name of the file: [Link]
Path of the file: C:\javaclass\[Link]
Parent name: C:\javaclass
Write mode: false
Read mode: false
File Reading & Writing in Java
In java, there multiple ways to read data from a file and to write data to a file. The most
commonly used ways are as follows.

✔ Using Byte Stream (FileInputStream and FileOutputStream)


✔ Using Character Stream (FileReader and FileWriter)

File Handling using Byte Stream


In java, we can use a byte stream to handle files. The byte stream has the following built-in
classes to perform various operations on a file.
● FileInputStream - It is a built-in class in java that allows reading data from a file.
This class has implemented based on the byte stream. The FileInputStream class
provides a method read() to read data from a file byte by byte.
● FileOutputStream - It is a built-in class in java that allows writing data to a file.
This class has implemented based on the byte stream. The FileOutputStream class
provides a method write() to write data to a file byte by byte.

The following example program that reads data from a file and writes the same to another
file using FileInoutStream and FileOutputStream classes.
Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 20
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22

Example:
import [Link].*;
public class FileReadingTest {

public static void main(String args[]) throws IOException {


FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("C:\\javaclass\\[Link]");
out = new FileOutputStream("C:\\javaclass\\[Link]");

int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
[Link]("Reading and Writing has been success!!!");
}
catch(Exception e){
[Link](e);
}finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();
}
}
}
}
Output:
Reading and Writing has been success!!!

File Handling using Character Stream


In java, we can use a character stream to handle files. The character stream has the
following built-in classes to perform various operations on a file.

Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 21


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
● FileReader - It is a built-in class in java that allows reading data from a file. This
class has implemented based on the character stream. The FileReader class provides
a method read() to read data from a file character by character.
● FileWriter - It is a built-in class in java that allows writing data to a file. This class
has implemented based on the character stream. The FileWriter class provides a
method write() to write data to a file character by character.

The following example program that reads data from a file and writes the same to another
file using FileReader and FileWriter classes.

Example:
import [Link].*;
public class FileIO {

public static void main(String args[]) throws IOException {


FileReader in = null;
FileWriter out = null;

try {
in = new FileReader("C:\\javaclass\\[Link]");
out = new FileWriter("C:\\javaclass\\[Link]");

int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
[Link]("Reading and Writing in a file is done!!!");
}
catch(Exception e) {
[Link](e);
}
finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();
}
}
}
}
Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 22
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Output:
Reading and Writing in a file is done!!!

RandomAccessFile in Java

In java, the [Link] package has a built-in class RandomAccessFile that enables a file to be accessed
randomly. The RandomAccessFile class has several methods used to move the cursor position in a
file.
A random access file behaves like a large array of bytes stored in a file.

RandomAccessFile Constructors
The RandomAccessFile class in java has the following constructors.

[Link]. Constructor with Description

1 RandomAccessFile(File fileName, String mode)


It creates a random access file stream to read from, and optionally to write to, the
file specified by the File argument.

2 RandomAccessFile(String fileName, String mode)


It creates a random access file stream to read from, and optionally to write to, a file
with the specified fileName.

Access Modes
Using the RandomAccessFile, a file may created in th following modes.
● r - Creates the file with read mode; Calling write methods will result in an
IOException.
● rw - Creates the file with read and write mode.
● rwd - Creates the file with read and write mode - synchronously. All updates to file
content is written to the disk synchronously.
● rws - Creates the file with read and write mode - synchronously. All updates to file
content or meta data is written to the disk synchronously.

RandomAccessFile methods
The RandomAccessFile class in java has the following methods.

[Link]. Methods with Description

1 int read()
It reads byte of data from a file. The byte is returned as an integer in the range
0-255.

Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 23


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link]. Methods with Description

2 int read(byte[] b)
It reads byte of data from file upto [Link], -1 if end of file is reached.

3 int read(byte[] b, int offset, int len)


It reads bytes initialising from offset position upto [Link] from the buffer.

4 boolean readBoolean()
It reads a boolean value from from the file.

5 byte readByte()
It reads signed eight-bit value from file.

6 char readChar()
It reads a character value from file.

7 double readDouble()
It reads a double value from file.

8 float readFloat()
It reads a float value from file.

9 long readLong()
It reads a long value from file.

10 int readInt()
It reads a integer value from file.

11 void readFully(byte[] b)
It reads bytes initialising from offset position upto [Link] from the buffer.

12 void readFully(byte[] b, int offset, int len)


It reads bytes initialising from offset position upto [Link] from the buffer.

13 String readUTF()
t reads in a string from the file.

14 void seek(long pos)


It sets the file-pointer(cursor) measured from the beginning of the file, at which the
next read or write occurs.

15 long length()
It returns the length of the file.

Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 24


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link]. Methods with Description

16 void write(int b)
It writes the specified byte to the file from the current cursor position.

17 void writeFloat(float v)
It converts the float argument to an int using the floatToIntBits method in class
Float, and then writes that int value to the file as a four-byte quantity, high byte first.

18 void writeDouble(double v)
It converts the double argument to a long using the doubleToLongBits method in
class Double, and then writes that long value to the file as an eight-byte quantity,
high byte first.

Example:
import [Link].*;

public class RandomAccessFileDemo


{
public static void main(String[] args)
{
try
{
double d = 1.5;
float f = 14.56f;

// Creating a new RandomAccessFile - "F2"


RandomAccessFile f_ref = new RandomAccessFile("C:\\javaclass\\[Link]", "rw");

// Writing to file
f_ref.writeUTF("Hello, Good Morning!");

// File Pointer at index position - 0


f_ref.seek(0);

// read() method :
[Link]("Use of read() method : " + f_ref.read());

f_ref.seek(0);

byte[] b = {1, 2, 3};


Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 25
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22

// Use of .read(byte[] b) method :


[Link]("Use of .read(byte[] b) : " + f_ref.read(b));

// readBoolean() method :
[Link]("Use of readBoolean() : " + f_ref.readBoolean());

// readByte() method :
[Link]("Use of readByte() : " + f_ref.readByte());

f_ref.writeChar('c');
f_ref.seek(0);

// readChar() :
[Link]("Use of readChar() : " + f_ref.readChar());

f_ref.seek(0);
f_ref.writeDouble(d);
f_ref.seek(0);

// read double
[Link]("Use of readDouble() : " + f_ref.readDouble());

f_ref.seek(0);
f_ref.writeFloat(f);
f_ref.seek(0);

// readFloat() :
[Link]("Use of readFloat() : " + f_ref.readFloat());

f_ref.seek(0);
// Create array upto [Link]
byte[] arr = new byte[(int) f_ref.length()];
// readFully() :
f_ref.readFully(arr);

String str1 = new String(arr);


[Link]("Use of readFully() : " + str1);

f_ref.seek(0);

Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 26


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
// readFully(byte[] b, int off, int len) :
f_ref.readFully(arr, 0, 8);

String str2 = new String(arr);


[Link]("Use of readFully(byte[] b, int off, int len) : " + str2);
}
catch (IOException ex)
{
[Link]("Something went Wrong");
[Link]();
}
}
}
Output:
Use of read() method : 0
Use of .read(byte[] b) : 3
Use of readBoolean() : true
Use of readByte() : 108
Use of readChar() : ¶
Use of readDouble() : 1.5
Use of readFloat() : 14.56
Use of readFully() : Ah?? Good Morning!
Use of readFully(byte[] b, int off, int len) : Ah?? Good Morning!

Serialization and Deserialization in Java

In java, the Serialization is the process of converting an object into a byte stream so that it
can be stored on to a file, or memory, or a database for future access. The deserialization is
reverse of serialization. The deserialization is the process of reconstructing the object from
the serialized state.

Using serialization and deserialization, we can transfer the Object Code from one Java
Virtual machine to another.

Serialization in Java

In a java programming language, the Serialization is achieved with the help of


interface Serializable. The class whose object needs to be serialized must implement the
Serializable interface.

Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 27


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
We use the ObjectOutputStream class to write a serialized object to write to a destination.
The ObjectOutputStream class provides a method writeObject() to serializing an object.

We use the following steps to serialize an object.


● Step 1 - Define the class whose object needs to be serialized; it must implement
Serializable interface.
● Step 2 - Create a file reference with file path using FileOutputStream class.
● Step 3 - Create reference to ObjectOutputStream object with file reference.
● Step 4 - Use writeObject(object) method by passing the object that wants to be
serialized.
● Step 5 - Close the FileOutputStream and ObjectOutputStream.

The serialization and deserialization process is platform-independent, it means you can


serialize an object on one platform and deserialize it on a different platform.

We must have to implement the Serializable interface for serializing the object.

Advantages of Java Serialization


It is mainly used to travel object's state on the network (that is known as marshalling).

The Serializable interface must be implemented by the class whose object needs to be
persisted.

The String class and all the wrapper classes implement the [Link] interface by
default.

Let's look at the following example program for serializing an object.

Example: [Link]
import [Link];

public class Student implements Serializable{

Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 28


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
int id;
String name;
public Student(int id, String name) {
[Link] = id;
[Link] = name;
}
}
In the above example, Student class implements Serializable interface. Now its objects can
be converted into stream. The main class implementation of is showed in the next code.

The ObjectOutputStream class is used to write primitive data types, and Java objects to an
OutputStream.

An ObjectInputStream deserializes objects and primitive data written using an


ObjectOutputStream.

Example:
import [Link].*;

public class Persist{


public static void main(String args[]){
try{
//Creating the object
Student s1 =new Student(102777,"VarunJoel");

//Creating stream and writing the object


FileOutputStream fout=new FileOutputStream("[Link]");
ObjectOutputStream out=new ObjectOutputStream(fout);
[Link](s1);
[Link]();

//closing the stream


[Link]();
[Link]("Operation done");
}catch(Exception e)
{[Link](e);}
}
}

Output:
Operation done
Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 29
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22

Java Deserialization
Deserialization is the process of reconstructing the object from the serialized state. It is the
reverse operation of serialization.

In a java programming language, the Deserialization is achieved with the help of class
ObjectInputStream. This class provides a method readObject() to deserializing an object.

We use the following steps to serialize an object.


Step 1 - Create a file reference with file path in which serialized object is available using
FileInputStream class.
Step 2 - Create reference to ObjectInputStream object with file reference.
Step 3 - Use readObject() method to access serialized object, and typecaste it to destination
type.
Step 4 - Close the FileInputStream and ObjectInputStream.

Let's see an example where we are reading the data from a deserialized object.

Example: [Link]
import [Link].*;

class Depersist{
public static void main(String args[]){

try{

//Creating stream to read the object


ObjectInputStream in=new ObjectInputStream(new FileInputStream("[Link]"));
Student s=(Student)[Link]();

//printing the data of the serialized object


[Link]([Link]+" "+[Link]);

//closing the stream


[Link]();
}catch(Exception e)
{[Link](e);}
}
}
Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 30
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Output:
102777 VarunJoel

Enum in Java

In java, an Enumeration is a list of named constants. The enum concept was introduced in
Java SE 5 version.

In java, the enumeration concept was defined based on the class concept. When we create an
enum in java, it converts into a class type. This concept enables the java enum to have
constructors, methods, and instance variables.

All the constants of an enum are public, static, and final. As they are static, we can access
directly using enum name.

The main objective of enum is to define our own data types in Java, and they are said to be
enumeration data types.

Creating enum in Java

To create enum in Java, we use the keyword enum. The syntax for creating enum is similar
to that of class.
In java, an enum can be defined outside a class, inside a class, but not inside a method.

Example:

enum WeekDay{
MONDAY, TUESDAY, WEDNESSDAY, THURSDAY, FRIDAY, SATURDAY,
SUNDAY;
}

public class EnumerationExample {


public static void main(String[] args) {

WeekDay day = [Link];

[Link]("Today is " + day);

[Link]("\nAll WeekDays: ");


for(WeekDay d:[Link]())
[Link](d);

Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 31


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22

}
Output:
Today is FRIDAY

All WeekDays:
MONDAY
TUESDAY
WEDNESSDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY
● Every enum is converted to a class that extends the built-in class Enum.
● Every constant of an enum is defined as an object.
● As an enum represents a class, it can have methods, constructors. It also gets a few
extra methods from the Enum class, and one of them is the values() method.

Autoboxing and Unboxing in Java


In java, all the primitive data types have defined using the class concept, these classes
known as wrapper classes. In java, every primitive type has its corresponding wrapper class.

All the wrapper classes in Java were defined in the [Link] package.

The following table shows the primitive type and its corresponding wrapper class.

[Link]. Primitive Type Wrapper class

1 byte Byte

2 short Short

3 int Interger

4 long Long

5 float Float

6 double Double

7 char Character

Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 32


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link]. Primitive Type Wrapper class

8 boolean Boolean

The Java 1.5 version introduced a concept that converts primitive type to corresponding
wrapper type and reverses of it.

Autoboxing in Java

In java, the process of converting a primitive type value into its corresponding wrapper class
object is called autoboxing or simply boxing. For example, converting an int value to an
Integer class object.

The compiler automatically performs the autoboxing when a primitive type value has
assigned to an object of the corresponding wrapper class.

Note:
We can also perform autoboxing manually using the method valueOf( ), which is provided
by every wrapper class.

Example: [Link]
import [Link].*;

public class AutoBoxingExample {

public static void main(String[] args) {

// Auto boxing : primitive to Wrapper


int num = 100;
Integer i = num;
Integer j = [Link](num);

[Link]("num = " + num + ", i = " + i + ", j = " + j);

}
}
Output:
num = 100, i = 100, j = 100

Auto un-boxing in Java

Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 33


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
In java, the process of converting an object of a wrapper class type to a primitive type value
is called auto un-boxing or simply unboxing. For example, converting an Integer object to
an int value.

The compiler automatically performs the auto un-boxing when a wrapper class object has
assigned to a primitive type.

Note:
We can also perform auto un-boxing manually using the method intValue( ), which is
provided by Integer wrapper class. Similarly every wrapper class has a method for auto
un-boxing.

Example: [Link]

import [Link].*;
public class AutoUnboxingExample {
public static void main(String[] args) {
// Auto un-boxing : Wrapper to primitive
Integer num = 200;
int i = num;
int j = [Link]();

[Link]("num = " + num + ", i = " + i + ", j = " + j);


}
}
Output:
num = 200, i = 200, j = 200

Generics in Java
The java generics is a language feature that allows creating methods and class which can
handle any type of data values. The generic programming is a way to write generalized
programs, java supports it by java generics.

The java generics is similar to the templates in the C++ programming language.

Note:
● Most of the collection framework classes are generic classes.
● The java generics allows only non-primitive type, it does not support primitive types
like int, float, char, etc.

Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 34


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
The java generics feature was introduced in Java 1.5 version. In java, generics used angular
brackets “< >”. In java, the generics feature implemented using the following.

● Generic Method
● Generic Class

Generic methods in Java


The java generics allows creating generic methods which can work with a different type of
data values.

Using a generic method, we can create a single method that can be called with arguments of
different types. Based on the types of the arguments passed to the generic method, the
compiler handles each method call appropriately.

Example: GenericFunctions
public class GenericFunctions {

public <T, U> void displayData(T value1, U value2) {

[Link]("(" + [Link]().getName() + ", " +


[Link]().getName() + ")");
}

public static void main(String[] args) {

GenericFunctions obj = new GenericFunctions();

[Link](45.6f, 10);
[Link](10, 10);
[Link]("Hi", 'c');
}

}
Output:
([Link], [Link])
([Link], [Link])
([Link], [Link])

In the above example code, the method displayData( ) is a generic method that allows a
different type of parameter values for every function call.

Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 35


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Generic Class in Java
In java, a class can be defined as a generic class that allows creating a class that can work
with different types.

A generic class declaration looks like a non-generic class declaration, except that the class
name is followed by a type parameter section.

Example:
public class GenericsExample<T> {
T obj;
public GenericsExample(T anotherObj) {
[Link] = anotherObj;
}
public T getData() {
return [Link];
}

public static void main(String[] args) {

GenericsExample<Integer> actualObj1 = new


GenericsExample<Integer>(100);
[Link]([Link]());

GenericsExample<String> actualObj2 = new


GenericsExample<String>("Java");
[Link]([Link]());

GenericsExample<Float> actualObj3 = new


GenericsExample<Float>(25.9f);
[Link]([Link]());
}
}
Output:
100
Java
25.9

Prepared by [Link] TEJA, Asst Professor, CSE Dept Page 36

You might also like