Uploaded by Yohans Wagaye

Chapter 6- File Handling System In Java

advertisement
HARAMAYA UNIVERSITY
COLLEGEOF COMPUTING AND INFORMATICS
DEPARTMENT OF SOFTWARE ENGINEERING
OBJECT ORIENTED P R O G R A M M I N G
CHAPTER 6- FILE HANDLING IN JAVA
Contents
2
1. Introduction
2. File Class
3. Java IO Stream
4. File Operation In Java
INTRODUCTION …(1)
3
• 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
INTRODUCTION …(2)
4
• 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.
INTRODUCTION …(3)
5
• 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.
INTRODUCTION …(4)
6
•
Java views each file as a sequential stream ofbytes
•
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
FILE CLASS…(1)
7
• File class in java is particularly useful for
• File class is used to perform the
retrieving information about files or directories
following activities:
• Check if a file exists
from disk.
• Create file/folder
• Before you can do anything with the file system
• Read the length of a file
or File class, you must obtain a File instance.
• Rename or move a file
• Example:
Here is how that is done:
• Delete a file
File file = new File("DriveLetter\\folderName\\fileName.txt");
Note: Objects of class File do not open files or provide any
file-processing capabilities
• Check if path is file or
directory
FILE CLASS…(2)
8
Examples:
File file = new File("D\\folderName\\fileName.txt");
boolean fileExists = file.exists(); //to check if a file exists,
long length = file.length(); //To read the length of a file in bytes,
file.renameTo (new File("D\\folderName\\newfileName.txt"); //to rename the file
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();
JAVA IO STREAM …(1)
9
• 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.
• No 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.
JAVA IO STREAM …(2)
10
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
JAVA IO STREAM …(3)
11
• 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.
Example: Images, Sounds, executable programs, etc.
o
CHARACTER STREAMS - Streams that input and output characters to files as a sequence of
characters Example: Plain text files (with .txt extension), web pages, user keyboard inputs, etc.
Format
Input
Output
Byte
InputStream
OutputStream
Character
Reader
Writer
JAVA IO STREAM …(4)
12
• N o matter where the data is coming from or going to and no matter what its type, the algorithms for
sequentially reading and writing data are basically the same as shown below:
Reading
Writing
•
Open a stream
•
Open a Stream
•
While more information, read information
•
While more information, write information
•
Close the stream
•
Close the stream
• 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.
JAVA IO STREAM …(5)
13
• 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.
Are Output streams
System.out →
Base Classes
•Java.io.InputStream
•Java.io.OutputStream
Both are abstractclasses of Byte Stream
•Java.io.Reader
•Java.io.Writer
Reader and Writer are both abstract classes of Character Stream
JAVA IO STREAM …(6)
14
BYTE STREAM CLASSES
15
FILEINPUTSTREAM
BYTEARRAYINPUTSTREAM
INPUTSTREAM
FILTERINPUTSTREAM
OBJECTINPUTSTREAM
BUFFEREDINPUTSTREAM
DATAINPUTSTREAM
OBJECT
FILEOUTPUTSTREAM
BYTEARRAYOUTPUTSTREAM
OUTPUTSTREAM
BUFFEREDOUTPUTSTREAM
FILTEROUTPUTSTREAM
DATAOUTPUTSTREAM
OBJECTOUTPUTSTREAM
CHARACTER STREAM
16
• 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.
CHARACTER STREAM CLASSES
17
INPUTSTREAMREADER
CHARARRAYREADER
READER
BUFFEREDREADER
FILEREADER
STRINGREADER
OBJECT
OUTPUTSTREAMWRITER
BUFFEREDWRITER
WRITER
FILEWRITER
CHARARRAYWRITER
STRINGWRITER
FILE OPERATIONS IN JAVA …(1)
18
FILE OPERATIONS IN JAVA …(2)
19
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();
}}}
1
FILE OPERATIONS IN JAVA …(3)
20
import java.io.File; //Import the File class
System.out.println("Absolute path: " +
2
public class GetFileInfo {
myObj.getAbsolutePath()); System.out.println("Writeable: "
public static void main(String[] args) {
+ myObj.canWrite());
File myObj= new File("F:\\Given
System.out.println("Readable " + myObj.canRead());
Courses\\2015\\OOP\\FileCreateByJava.txt");
System.out.println("File size in bytes " + myObj.length());
if (myObj.exists()) {
} else {
System.out.println("File name: " +
System.out.println("The file does not exist.");
myObj.getName());
}}}
FILE OPERATIONS IN JAVA …(4)
21
import java.io.FileWriter;
import java.io.IOException;
3
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();
}}
FILE OPERATIONS IN JAVA …(5)
22
import java.io.FileReader;
import java.io.IOException;
4
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(); } }
Thank You !!
Download