Unit – 7
Input and Output
Contents
• File
• Stream Classes
• Byte Stream Classes
• Character Stream Classes
File Handling
• A file is a sequence of records stored in binary format. A disk drive is
formatted into several blocks that can store records. File records are
mapped onto those disk blocks.
• A file is an object on a computer that stores data, information,
settings, or commands used with a computer program.
• To obtain properties of file/directory.
• To delete file/directory.
• To rename file/directory.
• To create directory.
• To read File.
• To write File.
• Absolute vs. Relative File Name
Absolute vs Relative File
Name
• An absolute file name (or full name) contains a file name with its
complete path.
• Absolute file names are machine dependent.
• For example,
• Windows: D:\MEFGI\[Link]
• directory path: D:\MEFGI, file name: [Link]
• UNIX: /home/MEFGI/[Link]
• directory path: /home/MEFGI, file name: [Link]
• A relative file name is in relation to the current working directory.
• The complete directory path for a relative file name is omitted.
• For example, [Link] is a relative file name.
File Handling
• Use the File class to obtain file/directory properties, to delete and
rename files/directories, and to create directories.
• Use the Scanner class for reading text data from a file.
• Use the PrintWriter class for writing text data to a file.
File Class
• File class is in [Link] package.
• The File class is intended to provide an abstraction that deals with
most of the machine-dependent complexities of files and path names
in a machine-independent fashion.
• The File class contains the methods for obtaining the properties of a
file/directory and for renaming and deleting a file/directory.
• However, the File class does not contain the methods for reading and
writing file contents.
The File Class
› File Constructors › getPath() method
› exists() method › getParent() method
› canRead() method › lastModified() method
› isDirectory() method › length() method
› isFile() mthod › listFile() method
› isAbsolute() method › delete() method
› isHidden() method › renameTo() method
› getAbsolutePath() method › mkdir() method
› getName() method
The Scanner Class
› Scanner(source: File) // Creates a Scanner that scans tokens from the
specified file.
› Scanner(source: String) // Creates a Scanner that scans tokens from the
specified string.
› close() // Closes this scanner.
› hasNext(): boolean // Returns true if this scanner has more data to be
read.
› next(): String // Returns next token as a string from this scanner.
› nextLine(): String // Returns a line ending with the line separator from
this scanner.
The Scanner Class
› nextByte(): byte // Returns next token as a byte from this scanner.
› nextShort(): short // Returns next token as a short from this scanner.
› nextInt(): int // Returns next token as an int from this scanner.
› nextLong(): long // Returns next token as a long from this scanner.
› nextFloat(): float // Returns next token as a float from this scanner.
› nextDouble(): double // Returns next token as a double from this scanner
Byte Streams and
Character Streams
• Stream is a channel in which data flow from sender to receiver.
• Sequence of objects and methods pipelined together to produce
results.
• An input object reads the stream of data from a file is called input
stream.
• The output object writes the stream of data to a file is called output
stream.
• These classes are found in [Link] package.
Byte Stream
Character Stream
ByteStream VS
CharacterStream
Character streams Byte streams
1. Meant for reading or writing to 1. Meant for reading or writing to binary
character- or text-based I/O such as data I/O such as executable files, image
text files, text documents, XML, and files, and files in low-level file formats
HTML files. such as .zip, .class, .obj and .exe.
2. Data dealt with is 16-bit Unicode 2. Data dealt with is bytes (i.e., units of 8-
characters. bit data).
3. Input and output character streams are 3. Input and output byte streams are
called readers and writers, respectively. simply called input streams and output
streams, respectively.
4. The abstract classes of Reader and
Writer and their derived classes in the 4. The abstract classes of Input Stream and
[Link] package provide support for Output Stream and their derived classes
character streams. in the [Link] package provide support
for byte streams.
Read and write operations on file
using InputStream and
OutputStream
//To write into a file using byte stream
import [Link].*;
class output
{public static void main(String args[])
{ String s ="This is my file";
int a=5;
Double d=5.35;
try
{
FileOutputStream fos= new FileOutputStream("[Link]");
DataOutputStream dos = new DataOutputStream(fos);
[Link](s);
[Link](a);
[Link](d);
[Link]();
}
catch(IOException ex)
{[Link]();}
}}
Read and write operations on file
using InputStream and
OutputStream
//To read from a file using byte stream
import [Link].*;
class input
{public static void main(String args[])
{
try
{ FileInputStream fin= new FileInputStream("[Link]"); //to read data from a file in bytes
DataInputStream din = new DataInputStream(fin); // read primitive Java data types
String line=null;
while((line =[Link]())!=null)
{
[Link](line);
}
[Link]();
}
catch(Exception ex)
{[Link]();}
}}
FileWriter and FileReader
//To read from a file using character stream
//To write into a file using character stream import [Link].*;
import [Link].*; class readerDemo
class writerDemo {
{ public static void main(String[] args)
public static void main(String[] args) {
try{
{
File f1= new File("[Link]");
try FileReader fr = new FileReader(f1);
{
FileWriter fw = new FileWriter("[Link]"); BufferedReader br=new
[Link]("Hello, Good Morning"); // [Link]("123"); BufferedReader(fr); //chaining
[Link](); String line=null;
} while((line=[Link]()) !=null)
catch(IOException ex) {
[Link](line);
{[Link]();}
}
}}
[Link]();
}
catch(Exception ex)
{[Link]();} }}
FileReader vs BufferedReader
FileReader reads file path
and returns data in byte
format. FileReader class
has the following two
methods: read() and
close().
BufferedReader reads
characters using another
Reader.
Methods: read(), readLine(),
close().
Questions
• File?
• What is a Stream?
• Two types of Streams?
• Byte Stream Classes used for?
• Character Stream Classes used for?
Summary
• File
• Stream Classes
• Byte Stream Classes
• Character Stream Classes
Next
• String class
• Character class
• StringBuffer class
• StringBuilder class
• Primitive type Wrapper classes
• Collections overview
• Collection interfaces
• Collection classes
• Maps
• Comparators
• Lists
• Vector class
• Stack class
• Scanner
• Formatter
END OF UNIT - 7
REFERENCE PURPOSE
REFERENCE PURPOSE
Example 2
PrintWriter and Reader
import [Link];
import [Link].*;
class Main { public class ReaderExample {
public static void main(String[] args) { public static void main(String[] args) {
try {
String data = "This is a text inside the file."; Reader reader = new FileReader(“[Link]");
int data = [Link]();
try { while (data != -1) {
PrintWriter output = new PrintWriter(“[Link]"); [Link]((char) data);
data = [Link]();
[Link](data); }
[Link](); [Link]();
} } catch (Exception ex) {
catch(Exception e) { [Link]([Link]());
[Link](); }
} }
} }
}
Reading Data from the
Web
• Just like you can read data from a file on your computer, you can read
data from a file on the Web.
• You can also access data from a file that is on the Web if you know
the file’s URL (Uniform Resource Locator—the unique address for a
file on the Web).
• For example, [Link]/[Link] is the URL for the file
[Link] located on the Google Web server.
Reading Data from the
Web
• For an application program to read data from a URL, you first need
to create a URL object using the [Link] class with this
constructor:
• public URL(String spec) throws MalformedURLException
try {
URL url = new URL("[Link]
}
catch (MalformedURLException ex)
{ [Link]();
}
Reading Data from the
Web
• For an application program to read data from a URL, you first need
to create a URL object using the [Link] class with this
constructor:
• public URL(String spec) throws MalformedURLException
try {
URL url = new URL("[Link]
}
catch (MalformedURLException ex)
{ [Link]();
}
Reading Data from the
Web
import [Link].*;
import [Link].*;
public class ReadURL {
public static void main(String[] args) throws Exception {
URL url = new URL("[Link]
BufferedReader read = new BufferedReader(
new InputStreamReader([Link]()));
String i;
while ((i = [Link]()) != null)
[Link](i);
[Link]();
}}
Abstract Class VS
Interface
Refer previous unit for examples.
Parameters Interface Abstract class
Speed Slow Fast
Multiple Inheritances Implement several Interfaces Only one abstract class
Structure Abstract methods Abstract & concrete methods
When to use Future enhancement To avoid independence
Inheritance/ A Class can implement multiple The class can inherit only
Implementation interfaces one Abstract Class
the interface cannot contain data
Data fields the class can have data fields.
fields.
In an abstract class, the abstract
In an abstract interface keyword, is
keyword is compulsory for
Abstract keyword optional for declaring a method as an
declaring a method as an
abstract.
abstract.
Abstract Class Example
Ex.: Shape (superclass), Circle and Rectangle (subclass)
Main Class
Class main{
Circle c = new circle();
Rectangle r = new Rectangle(); }
Interface
• Since abstract class allows concrete methods as well, it does not
provide 100% abstraction.
• You can say that it provides partial abstraction.
• Interfaces are used for 100% abstraction (full abstraction)
Syntax:
modifier interface InterfaceName {
/** Constant declarations */
/** Abstract method signatures */
}
The Comparable Interface
• Suppose you want to design a generic method to find the larger of
two objects of the same type, such as two students / dates / circles
/ rectangles / etc.
• In order to accomplish this, the two objects must be comparable,
so the common behavior for the objects must be comparable.
• Java provides the Comparable interface for this purpose.
• The Comparable interface defines the compareTo method for
comparing objects.
The interface is defined as follows:
package [Link];
public interface Comparable<E> {
public int compareTo(E o);
}
The Comparable Interface
• The Comparable interface is a generic interface.
• The generic type E [Comparable<E>] is replaced by a concrete type
when implementing this interface.
class circle implements Comparable<Circle> {
public int compareTo(Circle o){
...
}
}
The Comparable Interface
SortComparableObjects
import [Link].*;
public class Main {
public static void main(String[] args) {
String[] cities = {"Savannah", "Boston", "Atlanta", "Tampa"};
[Link](cities);
for (String city: cities)
Output:
[Link](city + " "); Atlanta Boston Savannah Tampa
[Link](); 54623239292 432232323239292 2323231092923992
BigInteger[] hugeNumbers = {new BigInteger("2323231092923992"),
new BigInteger("432232323239292"),
new BigInteger("54623239292")};
[Link](hugeNumbers);
for (BigInteger number: hugeNumbers)
[Link](number + " ");
}}
The Comparable Interface
class Student implements Comparable<Student>{
int rollno;
String name;
int age; import [Link].*;
Student(int rollno,String name,int age){ public class TestSort2{
[Link]=rollno; public static void main(String args[])
[Link]=name; {
[Link]=age; ArrayList<Student> al=new ArrayList<St
} udent>();
[Link](new Student(101,"Vijay",23));
public int compareTo(Student st){ [Link](new Student(106,"Ajay",27));
if(age==[Link]) [Link](new Student(105,"Jai",21));
return 0;
else if(age>[Link]) [Link](al);
return 1; for(Student st:al){
else [Link]([Link]+" "+[Link]
return -1; +" "+[Link]);
} }
} }
}
The Cloneable Interface
• Often it is desirable to create a copy of an object. To do this, you
need to use the clone method and understand the Cloneable interface.
• The Cloneable interface specifies that an object can be cloned.
• An interface contains constants and abstract methods, but the
Cloneable interface is a special case. The Cloneable interface in the
[Link] package is defined as follows:
package [Link]; This interface is empty. An interface with an empty
body is referred to as a marker interface. A marker
public interface Cloneable { interface does not contain constants or methods. It
} is used to denote that a class possesses certain
desirable properties. A class that implements the
Cloneable interface is marked cloneable, and its
objects can be cloned using the clone() method
defined in the Object class.
The Cloneable Interface
package [Link];
public interface Cloneable {
}
• This interface is empty. An interface with an empty body is referred to
as a marker interface.
• A marker interface does not contain constants or methods. It is used to
denote that a class possesses certain desirable properties.
• A class that implements the Cloneable interface is marked cloneable,
and its objects can be cloned using the clone() method defined in the
Object class.
• Many classes in the Java library (e.g., Date, Calendar, ArrayList etc.)
implement Cloneable. Thus, the instances of these classes can be
cloned.
The Cloneable Interface
• Creating Copy of Java Object
• We can create a replica or copy of java object by
• Creating a copy of object in a different memory location. This is
called a Deep copy.
• Creating a new reference that points to the same memory location.
This is also called a Shallow copy.
The Cloneable Interface
//DeepCopy
//ShallowCopy class Main implements Cloneable
class Main {
{ public int x = 30;
int x = 30;
public static void main(String args[])
public static void main(String args[]) {
{ Main obj1 = new Main();
Main obj1 = new Main();
// it will copy the reference, not value
//SCopy obj2 = obj1;
// it will copy the reference, not value try{
Main obj2 = obj1; Main obj2 = (Main)[Link]();
obj2.x = 6;
obj2.x = 6; [Link]("The value of x is: " + obj1.x);
[Link]("The value of x is: " + obj1.x); [Link]("The value of x is: " + obj2.x);
} } }
catch(Exception e){[Link](e);}
} }
The Cloneable Interface
Shallow Copy Deep Copy
Reference Programs
Reading Data from the
Web
import [Link];
public class ReadFileFromURL {
public static void main(String[] args) {
[Link]("Enter a URL: ");
String URLString = new Scanner([Link]).next();
try {
[Link] url = new [Link](URLString);
int count = 0;
Scanner input = new Scanner([Link]());
while ([Link]()) {
String line = [Link]();
count += [Link]();
}
[Link]("The file size is " + count + " characters");
}
catch ([Link] ex) {
[Link]("Invalid URL");
}
catch ([Link] ex) {
[Link]("I/O Errors: no such file");
}
}
}
ByteStream VS
CharacterStream
import [Link].*;
class CopyFile
{
public static void main(String args[])
{
try
{
FileInputStream fr = new FileInputStream("[Link]");
FileOutputStream fw = new FileOutputStream(“[Link]");
int i =0;
while ((i=[Link]())!=-1){
[Link](i);
• First place the image in
}
[Link](); the proper folder.
[Link](); • This program will copy
[Link](); the picture as it is in the
[Link]("File copied successfully......."); name of “copy”.
} • This will work fine.
catch(Exception e)
{
[Link](e);
}
}
}
ByteStream VS
CharacterStream
import [Link].*;
class CopyFile
{
public static void main(String args[])
{
try
{
FileReader fr = new FileReader("[Link]");
FileWriter fw = new FileWriter("[Link]");
• TRY int i =0;
• First place the image in while ((i=[Link]())!=-1){
the proper folder. [Link](i); • This will work fine for
• Try to create a copy as } the text.
like previous program it [Link]();
will not copy the image. [Link]();
• The copied image will be [Link]();
corrupted. [Link]("File copied successfully.......");
}
catch(Exception e)
{
[Link](e); } } }
ByteStream VS
CharacterStream
• Figure out the reasons for the previous two programs.
Thank you
End of Unit 7