0% found this document useful (0 votes)
20 views23 pages

Chapter 7 Files and Streams

Uploaded by

ktesfaneh2
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)
20 views23 pages

Chapter 7 Files and Streams

Uploaded by

ktesfaneh2
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
You are on page 1/ 23

Object Oriented Programming

Chapter - 7
Files and Streams

Compiled By Yohans Samuel(MSc)

1
Contents

Files and Streams

1. Introduction
2. File
3. I/O Stream classes
4. File Operations

2
Introduction (1)
• In programs, storage of data in variables and arrays is temporary
because: the data is lost when a local variable goes out of scope or
when the program terminates
• Computers use files for long-term retention of large amounts of data,
even after the programs that created the data terminate.
• We refer to data maintained in files as persistent data because it exists
beyond the duration of program execution.
• Computers store files on secondary storage devices such as hard disks,
optical disks and magnetic tapes

3
Introduction (2)
• File handling implies how to read from and write to file in java.
• Java provides the basic I/O package for reading and writing
streams.
• File class from the java.io package, allows to do all input and
output operations with different formats of files.
• In order to use the File class, you need to create an object of the
class and specify the filename or directory name.

4
Introduction (3)
• The file system is the structure by which computers
manage files on their hard drives.
• In Window, Mac, and Linux the file system uses
directories or folders to organize files.
• Sometimes your application will need to read input
data from a file or write the output data to a file.
• Java offers classes in the java.io package to facilitate
these input/output (I/O) operations.
• File is a collection of related records.

5
Introduction (4)
• Java views each file as a sequential stream of bytes
• Stream represent uniform, easy to use, object oriented interface b/n the
program and I/O devices.
• Streams treat all external source and destinations of data the same way:
as "streams of information

• Input/Output(I/O) communication between a computer program and


external sources and destinations of information involves Reading
and Writing:

o Reading input from a source and

o Writing output to a destination

6
File (1)
• File class in java is particularly useful for retrieving information about files or
directories from disk.
• Before you can do anything with the file system or File class, you must obtain a
File instance.
• Here is how that is done:
• File file = new File("DriveLetter\\folderName\\fileName.txt");
• Objects of class File do not open files or provide any file-processing capabilities
• File class is used to perform the following activities:
• Check if a file exists
• Create file/folder
• Read the length of a file
• Rename or move a file
• Delete a file
• Check if path is file or directory

7
File (2)
• File file = new File("D\\folderName\\fileName.txt");

//to check if a file exists,

• boolean fileExists = file.exists();

//To read the length of a file in bytes,


• long length = file.length();
//to rename the file

• file.renameTo (new File("D\\folderName\\newfileName.txt");

• file.delete(); //To delete a file

//To check if a file is a file or a directory and list files in the directory File file

= new File("D\\folderName");
• boolean isDirectory = file.isDirectory();

8
Java IO Stream (1)
• An IO Stream represent an Input source or output destination.
• A stream can represent different kinds of sources and destinations, including disk files,
devices, other program, and memory arrays.
• Stream supports different types of data, including simple bytes, primitive data types,
localized characters, and objects.

• Some streams simply pass on data; others manipulate and transform the data in useful
ways.
• N o matter how they work internally, all streams present the same simple model to
programs that use them.

• A stream is sequence of data.

• The data source and destination can be anything that holds, generates, or consumes data.

9
Java IO Stream (2)
Java streams are classified into two basic types:

A program uses an INPUT STREAM to


read data from a source, one item at a
time.

Reading Information into a program

A program uses an OUTPUT STREAM


to write data to destination, one item
at a time.

Writing Information from a program

10
Java IO Stream (3)
• File streams can be used to Input and Output data in two
formats:
o BYTE- STREAMS - Streams that input and output bytes to
files in its binary format.
o Example: Images, Sounds, executable programs, etc.
o CHARACTER STREAMS - Streams that input and output
characters to files as a sequence of characters
o Example: Plain text files (with .txt extension), web pages, user keyboard inputs,
etc.
Format Input Output

Byte InputStream OutputStream

Character Reader Writer

11
Java IO Stream (4)
• N o matter where the data is coming from or going to and no matter what its
type, the algorithm for sequentially reading and writing data are basically the
same as shown below:
• java.io package contains a collection of stream classes that support these
algorithms for reading and writing.
• To use these classes, a program needs to import the java.io package.
Reading
• Open a stream
• While more information, read information
• Close the stream
Writing
• Open a Stream
• While more information, write information
• Close the stream
12
Java IO Stream (5)
• There are three I/O streams predefined and always open for any java program.
• System.in:-Input Stream connected to the keyboard.
System.out:-Output Stream connected to output devices.

• System.out Are Output streams


• The following are both abstract classes of ByteSteam
• java.io.InputStream

• java.io.OutputStream

• The following are both abstract classes of CharacterStream


• java.io.Reader

• java.io.Writer

13
Java IO Stream (6)

14
ByteStream Classes

15
Character Stream Classes (1)
• Character streams provide a convenient means for handling input
and output of characters.
• They use Unicode and, therefore, can be internationalized.
• Also, in some cases, character streams are more efficient than byte
streams.
• Reader and Writer classes support essentially same operations as
InputStream and OutputStream, except that their methods operate on
character arrays and strings.
• Reader and Writer are the abstract super-classes for character
streams in java.io.
• Reader provides the API and partial implementation for readers
streams that read 16-bit characters and
• Writer provides the API and partial implementation for writers
streams that write 16-bit characters.
16
Character Stream Classes (2)

17
File Operations (1)

18
File Operations (2)
import java.io.File;
import java.io.IOException;
public class CreateFile{
public static void main(String[] args) {
try {
File myObj = new File("F:\\Given Courses\\2015\\Silesh.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}}}

19
File Operations (3)
import java.io.File; // Import the File class
public class GetFileInfo {
public static void main(String[] args) {
File myObj= new File("F:\\GivenCourses\\2015\\OOP\\FileCreateByJava.txt");
if (myObj.exists()) {
System.out.println("File name: " + myObj.getName());
System.out.println("Absolute path: " + myObj.getAbsolutePath());
System.out.println("Writeable: "+ myObj.canWrite());
System.out.println("Readable " + myObj.canRead());
System.out.println("File size in bytes " + myObj.length());
} else {
System.out.println("The file does not exist.");
}}}

20
File Operations (4)
import java.io.FileWriter; 3
import java.io.IOException;
public class CharacterStreamWriter{
public static void main(String[] args) throws IOException{
FileWriter charOutput = new FileWriter("F:\\Given
Courses\\2015\\OOP\\File_Handling_Examples.txt");
charOutput.write("This is java file system");
charOutput.close();
}}

21
File Operations (5)
import java.io.FileReader;
import java.io.IOException;
public class CharacterStreamReader{
public static void main(String[] args) throws IOException {
FileReader charInput= new FileReader("F:\\Given
Courses\\2015\\OOP\\File_Handling_Examples.txt");
int ch;
while ((ch = charInput.read()) != -1)
System.out.print((char)ch);
charInput.close();
}
}

22
Questions?

23

You might also like