chapter 2(IO and stream)/chapter 2, IO and stream

amarehope21 21 views 41 slides Oct 19, 2024
Slide 1
Slide 1 of 41
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41

About This Presentation

chapter 2(IO and stream)/chapter 2, IO and stream


Slide Content

Chapter -2 Streams and File I/O 1

Streams and File I/O 2 Java uses the concept of a stream to make I/O operation fast. I/O means Input/Output. The java.io package contains all the classes required for input and output operations A stream can be defined as a sequence of data . An I/O Stream is a sequence of data that is read from a source and write to a destination.

Streams and File I/O 3 Stream : an object that either delivers data to its destination (screen , file, etc.) or that takes data from a source (keyboard, file , etc .) It acts as a buffer between the data source and destination Input stream : a stream that provides input to a program System.in is an input stream Output stream : a stream that accepts output from a program System.out is an output stream.

Streams and File I/O 4 All these streams represent an input source and an output destination . A stream connects a program to an I/O object System.out connects a program to the screen System.in connects a program to the keyboard Input Output

The Java File Class 5 Java File class represents the files and directory pathnames in an abstract manner. The File class is useful for retrieving information about files or directories from disk. The File class contains the methods for obtaining the properties of a file/directory and for renaming and deleting a file/directory. The File class has different methods which can be used to manipulate the files . Absolute path: An absolute file name (or full name) contains a file name with its complete path and drive letter. C:\comp\cs.txt Relative path: A relative file name is in relation to the current working directory . cs.txt

Methods in Java File Class 6 boolean canExecute ():     Tests whether the application can execute the file denoted by this pathname. boolean canRead () :  This function returns true, if the program can read the file. boolean canWrite ():  This boolean function returns true if it can write over the contents of the file. If not, it returns false. int compareTo (File pathname):  This function compares two pathnames lexicographically. boolean createNewFile ():   creates a new file that is empty following the abstract pathname. If it cannot then it returns false. static File createTempFile (String prefix, String suffix):  As the name suggests this function creates a temporary file inside the default temporary file library.

Methods in Java File Class 7 boolean delete() :  Deletes the file or directory denoted by this abstract pathname. boolean equals(Object obj ) :  Tests this abstract pathname for equality with the given object. boolean exists()  : Tests whether the file or directory denoted by this abstract pathname exists. String getAbsolutePath () :  Returns the absolute pathname string of this abstract pathname. long getFreeSpace () :  Returns the number of unallocated bytes in the partition . String getName () :  Returns the name of the file or directory denoted by this abstract pathname. String getParent () :  Returns the pathname string of this abstract pathname’s parent. File getParentFile () :  Returns the abstract pathname of this abstract pathname’s parent .

Methods in Java File Class 8 String getPath () :  Converts this abstract pathname into a pathname string. boolean isDirectory () :  Tests whether the file denoted by this pathname is a directory. boolean isFile () :  Tests whether the file denoted by this abstract pathname is a normal file. boolean isHidden () :  Tests whether the file named by this abstract pathname is a hidden file. long length() :  Returns the length of the file denoted by this abstract pathname. String[] list() :  Returns an array of strings naming the files and directories in the directory . File [] listFiles () :  Returns an array of abstract pathnames denoting the files in the directory. boolean mkdir () :  Creates the directory named by this abstract pathname.

Methods in Java File Class 9 boolean renameTo (File dest ) :  Renames the file denoted by this abstract pathname. boolean setExecutable ( boolean executable) :  A convenience method to set the owner’s execute permission. boolean setReadable ( boolean readable) :  A convenience method to set the owner’s read permission. boolean setReadable ( boolean readable, boolean ownerOnly ) :  Sets the owner’s or everybody’s read permission. boolean setReadOnly () :  Marks the file or directory named so that only read operations are allowed. boolean setWritable ( boolean writable)  : A convenience method to set the owner’s write permission. String toString () :  Returns the pathname string of this abstract pathname. URI toURI () :  Constructs a file URI that represents this abstract pathname.

Methods in Java File Class 10 package fileio ; import java.io.IOException ; public class FileIO { public static void main(String[] args ) { java.io.File file = new java.io.File (" F :\\poly\\first.txt "); try{ if( file. createNewFile ()){ System.out.println ("New File created"); }else{ System.out.println ("File already Exists"); } } catch( IOException e){ System.out.println ("File not found"); } } } b oolean createNewFile ():   creates a new file that is empty following the abstract pathname. If it cannot then it returns false.

Methods in Java File Class 11 File operations can typically cause unexpected situations that the program is not capable of handling ( for example , if we try to open a file for reading, and specify a filename that does not exist). Such situations are called exceptions . For example, the methods for opening a file for reading can generate an exception of type IOException . public static void main(String[] args ) throws IOException { ... body... }

Methods in Java File Class 12

File Input Output 13 Data stored in a Text file are represented in human-readable form. Data stored in a binary file are represented in binary form . You cannot read binary files. Binary files are designed to be read by programs. For example , the Java source programs are stored in text files and can be read by a text editor, but the Java .class files are stored in binary files and are read by the JVM . The advantage of binary files I/O are more efficient to process than text files I/O, because binary file I/O does not require encoding and decoding . But Text file I/O requires encoding and decoding .

File Input Output 14 The Scanner class uses for reading text data from a file and the PrintWriter class uses for writing text data to a file. Text data is read using the Scanner class and written using the PrintWriter class . Scanner input = new Scanner( new File(filename)); PrintWriter output = new PrintWriter (filename);

Writing Data Using PrintWriter 15 The java.io.PrintWriter class can be used to create a file and write data to a text file. To create a PrintWriter object for a text file use the following steps: Open the file for writing by creating an object of the class FileWriter or File associated to the name of the file, and creating an object of the class PrintWriter associated to the FileWriter object just created ; write text on the file by using the print and println methods of the PrintWriter object; close the file when we are finished writing to it. String filePath = “c:/poly/data.txt”; //File file = new File( filePath ); PrintWriter output = new PrintWriter ( filePath );

Writing Data Using PrintWriter 16

Writing Data Using PrintWriter 17

18 import java.io .*; public class FileIO { public static void main(String[] args ) throws IOException { String filePath = "F :/poly/study.txt "; String content = " Data to be written on the file "; FileWriter file = new FileWriter ( filePath ); //File file = new File( filePath ); PrintWriter out = new PrintWriter (file); out.println (content); out.close (); } } Writing Data Using FileWriter & PrintWriter

Writing Data Using FileWriter & PrintWriter 19 The invocation of the constructor of the class FileWriter has the effect of creating a file that is ready to be written on. If the file already exists, all its contents is erased first. To append text to an already existing file without erasing the previous content of the file, we have to use the constructor with the signature FileWriter (String, boolean ), specifying the value true for the second argument . FileWriter file = new FileWriter ( filePath , true );

Writing Data Using FileWriter & PrintWriter 20 Example : Method that writes an array of strings on a file. Both the array of strings and the filename are passed as parameters to the method. import java.io.*; public static void saveArray (String[] v, String filename) throws IOException { FileWriter f = new FileWriter (filename); PrintWriter out = new PrintWriter (f); for ( int i = 0; i < v.length ; i ++) out.println (v[ i ]); out.close (); f.close (); }

Reading Data Using Scanner 21 To read from a file, create a Scanner for a file, as follows: This example creates an instance of Scanner and reads data from the file scores.txt . String filePath = “c:/poly/data.txt”; File file = new File( filePath ); Scanner input = new Scanner(file);

Reading Data Using Scanner 22

Reading Data Using Scanner 23

Reading Data Using File Reader 24 To read strings of text from a file we have to : Open the file for reading by creating an object of the class FileReader and an object of the class BufferedReader associated to the FileReader object we have just created; R ead the lines of text from the file by using the readLine method of the BufferedReader object; Close the file when we are finished reading from it.

Reading Data Using File Reader 25 If the file that we want to open for reading does not exist, then an exception of type FileNotFoundException is raised when the object FileReader is created. After we have opened the file, we start reading from its first line. Then, each time we invoke the method readLine , we advance the input to the next line, so that each invocation of readLine will read the following line of text in the file. // opening the file for reading FileReader f = new FileReader ("test.txt "); BufferedReader in = new BufferedReader (f); // reading a line of text from the file String line = in.readLine (); // closing the file f.close (); String line; while ((line= in.readLine ())!= null){ System.out.println (line ); } fr.close ();

Renaming and Deleting a file in Java 26 To delete a file (i.e., remove it completely from the mass-storage device), we invoke the method delete on an object of type File created with the name of the file to delete . File f1 = new File("garbage.txt"); boolean b = f1.delete(); // if b is true, then the file has been deleted successfully The constructor of the class File does not generate an exception if the file does not exist. The result of the deletion operation is returned by the delete method.

Renaming and Deleting a file in Java 27 To rename a file , we invoke the method renameTo on two objects of type File that represent respectively the file to rename, and the new name to give to the file. File f1 = new File("oldname.txt"); File f2 = new File("newname.txt"); boolean b = f1.renameTo(f2); // if b is true, then the file has been renamed successfully The file oldname.txt , if it exists, is renamed to the file newname.txt . If there already exists a file named newname.txt , then it is overwritten . The result of the renaming operation is returned by the renameTo method.

Input/ Output Streams 28 Java defines a common way of handling all input/output devices, namely as producers/consumers of sequences of data (characters ). The concept of stream represents a sequence of data generated by a input device or consumed by an output device . All classes used to define the various streams are derived from the classes InputStream and OutputStream . We have different types of streams Binary I/O Stream Character I/O Stream Standard I/O Stream

Binary I/O Stream 29 Computers do not differentiate between binary files and text files. All files are stored in binary format, and thus all files are essentially binary files. Text I/O requires encoding and decoding. Text I/O is built upon binary I/O to provide a level of abstraction for character encoding and decoding. The JVM converts a Unicode to a file specific encoding when writing a character and coverts a file specific encoding to a Unicode when reading a character .

Binary I/O Stream 30 For example, suppose you write the string "199" using text I/O to a file. The ASCII code for character 1 is 49 ( 0x31 in hex) and for character 9 is 57 ( 0x39 in hex). Thus, to write the characters 199 , three bytes— 0x31 , 0x39 , and 0x39 —are sent to the output. Binary I/O does not require conversions. When you write a byte to a file, the original byte is copied into the file. When you read a byte from a file, the exact byte in the file is returned. For example, a byte-type value 199 is represented as 0xC7 in the memory and appears exactly as 0xC7 in the file.

Binary I/O Stream 31 Text I/O Program The Unicode of the Character e.g. 199 Binary I/O Program A byte is read/written e.g. 199 00110001 00111001 00111001 0x31 0xC7 The Same byte in the file 11000111 The encoding of the Character is stored in the file 0x39 0x39 Encoding/Decoding

Binary I/O Stream 32 Binary I/O is more efficient than text I/O, because binary I/O does not require encoding and decoding . Text I/O representation of 199 in text format require 3 bytes (one for each character), but Binary I/O require 1 byte to represent 199. Binary files are independent of the encoding scheme on the host machine and thus are portable. Java programs on any machine can read a binary file created by a Java program. This is why Java class files are binary files . Java class files can run on a JVM on any machine .

Binary I/O Stream 33 The abstract InputStream is the root class for reading binary data and the abstract OutputStream is the root class for writing binary data .

Binary I/O Stream 34 Java byte streams are used to perform input and output of 8-bit bytes . Though there are many classes related to byte streams but most frequently used classes are, FileInputStream and FileOutputStream . FileInputStream / FileOutputStream is for reading/writing bytes from/to files. FileInputStream / FileOutputStream associates a binary input/output stream with an external file. All the methods in FileInputStream / FileOuptputStream are inherited from its superclasses .

Binary I/O Stream 35 FileInputStream To construct a FileInputStream , use the following constructors : public FileInputStream (String filename) public FileInputStream (File file) A java.io.FileNotFoundException would occur if you attempt to create a FileInputStream with a non-existent file .

Binary I/O Stream 36 FileOutputStream To construct a FileOutputStream , use the following constructors: public FileOutputStream (String filename) public FileOutputStream (File file) public FileOutputStream (String filename, boolean append) public FileOutputStream (File file , boolean append) If the file does not exist, a new file would be created. If the file already exists, the first two constructors would delete the current contents in the file. To retain the current content and append new data into the file, use the last two constructors by passing true to the append parameter .

Binary I/O Stream 37 import java.io .*; public class FileIO { public static void main(String[] args ) throws IOException { // Create an output stream to the file FileOutputStream output = new FileOutputStream ("F :/poly/temp.txt "); // Output values to the file for ( int i = 1; i <= 10; i ++) output. write ( i ); // Close the output stream output. close (); // Create an input stream for the file FileInputStream input = new FileInputStream ("F :/poly/temp.txt "); // Read values from the file int value; while ((value = input. read ()) != -1) System.out.print (value + " "); // Close the output stream input.close (); } } This program uses binary I/O to write ten byte values from 1 to 10 to a file named temp.txt and reads them back from the file

Character I/O Stream 38 Character Stream is an input and output data as a sequence of characters. Java b yte streams are used to perform input and output of 8-bit bytes , whereas Java Character streams are used to perform input and output for 16-bit Unicode . All character stream classes are also descended from two abstract classes Read and Writer . The most frequently used character stream classes are : FileReader and FileWriter .

Character I/O Stream 39

Standard I/O Stream 40 All the programming languages provide support for standard I/O where the user's program can take input from a keyboard and then produce an output on the computer screen. Java provides the following three standard streams: Standard Input - This is used to feed the data to user's program and usually a keyboard is used as standard input stream and represented as System.in . Standard Output - This is used to output the data produced by the user’s program and usually a computer screen is used for standard output stream and represented as System.out . Standard Error - This is used to output the error data produced by the user’s program and usually a computer screen is used for standard error stream and represented as System.err .

41 Thank You!