chapter 14chapter 14 file input/output · pdf fileadvantage: the programmer does not need to...
TRANSCRIPT
![Page 1: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/1.jpg)
Chapter 14Chapter 14File Input/Output
• Streams and Files• File Stream Processing• Text File I/O• Text File I/O• The File Class• Binary File I/O
1
![Page 2: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/2.jpg)
FilesFile:
Junrong 16 1.76
ChooEng 17 1.77
• Data in Files
SiuCheng 18 1.78
• Data in Files– Bits– Byte
Record: Junrong 16 1.76
y– Fields– Records
Fil
Field:J unrong
– Files
• File organizationByte: 01001010
2– sequential files– random filesBit: 1
![Page 3: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/3.jpg)
Stream I/O All file I/O operations are carried out by means of streams. A stream is a sequence of characters. It connects a q
program to a device (or file) and transfers the data in (input stream) and out (output stream) from the program.
Input Stream Output StreamProgram
Advantage: the programmer does not need to write
Input Stream
Keyboard Display
Output Streamg
Advantage: the programmer does not need to write specific input/output functions for different devices such as keyboard display printer etckeyboard, display, printer, etc.
Example Input files: keyboard, camera, disk drive, ..Output files: disk drive, tape drive, printer, monitor, ...
3
p , p , p , ,
![Page 4: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/4.jpg)
The Standard Java Stream Objects
Stream Object Devicej
standard input System.in input - normally the keyboard
standard output System out output normally the displaystandard output System.out output - normally the display
standard error System.err error message - the display
System.in ProgramSystem.out
Keyboard DisplaySystem.err
4
![Page 5: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/5.jpg)
Binary vs Text Files Disk file streams work in a similar way as the standard
input/output streams.p p A file stream can be viewed as a continuous sequence of
bytes. Two modes of disk access: text mode and binary mode. Text mode:
used for text files data are stored and accessed as a– used for text files, data are stored and accessed as a sequence of characters.– character-based files.
Binary mode:– used for binary files, data are stored and accessed as
f b ta sequence of bytes.– byte-based files: data are stored in binary digits of 0 and 1
5
and 1.
![Page 6: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/6.jpg)
End-of- File Marker It is a special character in the file that is used to indicate
the end of a file. Text file
the character ‘\n’ is an end-of-line placed at the end of a line. end-of-file (EOF) character will be placed at the end of a filea file. Reading of files can be controlled using end-of-file marker.
Binary file No end-of-file character
N d i l t h i t d d t f bi Need a special technique to read data from a binary file – to be discussed later.
6
![Page 7: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/7.jpg)
Chapter 14Chapter 14File Input/Output
• Streams and Files• File Stream Processing• Text File I/O• Text File I/O• The File Class• Binary File I/O
7
![Page 8: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/8.jpg)
File Stream Processingg
Basic file stream classes for text and binary files:
Mode For Text Files For Binary FilesInput Use the FileReader class Use the FileInputStream classInput Use the FileReader class Use the FileInputStream classOutput Use the FileWriter class Use the FileOutputStream class
8
![Page 9: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/9.jpg)
Processing Text Filesimport java io *;import java.io.*;public class ProcessingFileStreams {
public static void main(String[] args) {try {try {
// Step 1: Create and open file streams FileReader iStream = new FileReader("input.txt");FileWriter oStream = new FileWriter("output.txt");FileWriter oStream new FileWriter( output.txt );// Step 2: Perform Read/Write Operationint data;data = iStream.read();();oStream.write(data);// Step 3: Close file streamsiStream.close();oStream.close();
}catch (IOException e) {
System.out.println("IO Error!" + e.getMessage());e.printStackTrace();System.exit(0);
9
}}
}
![Page 10: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/10.jpg)
Processing Text Filesinput txt output txt
This is a test.This is only a test.
input.txtT
output.txt
This is only a test.
Program opens file: Program open file output.txt*.input.txt*. Readsfirst character fromfile
Write character to file.
Both files are “closed”file.
*If file doesn’texist an exception is
Both files are closed . Program ends.
*If t t t t l d i t it t t i d l t
10
If file doesn texist an exception is thrown (and caught).
*If output.txt already exist, its content is delete.
![Page 11: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/11.jpg)
Buffered Stream I/OComputer
D t
Input Buffer
Computer
Program
Data
Fileg
Data
Output Buffer
Buffering is used for input and output. g p p I/O operations are expensive that involve mechanical
movement.A b ff i f l ti th t i d t A buffer is a sequence of memory locations that is used to store data temporarily between the program and an I/O device
11
device. Buffered I/O will be used in programming file I/O.
![Page 12: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/12.jpg)
Chapter 14Chapter 14File Input/Output
• Streams and Files• File Stream Processing• Text File I/O• Text File I/O• The File Class• Binary File I/O
12
![Page 13: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/13.jpg)
T t Fil I/OText File I/O
Stream class hierarchyy
13
![Page 14: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/14.jpg)
Output Stream Classes for Writing Text Files
Cl D i ti M th dClass Description MethodsFileWriter Provides the basic
stream for text write(), flush(), close()
output.BufferedWriter Provides output
buffering to write(), flush(), close()
gimprove performance.
PrintWriter Provides a number print(char) print(String)PrintWriter Provides a number of useful output methods for processing.
print(char), print(String), print(int), print(float), print(double), print(boolean), and the corresponding println()processing. p g p ()methods, flush(), close()
14
![Page 15: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/15.jpg)
Writing Text Files using a Buffered Stream Objectimport java.io.*;public class WritingTextFiles {public class WritingTextFiles {
public static void main(String[] args) {try {
FileWriter fwStream = new FileWriter("data.txt");( )BufferedWriter bwStream =
new BufferedWriter(fwStream);PrintWriter pwStream = new PrintWriter(bwStream);int num;for (num=0; num<5; num++)
pwStream.println("Number = " + num*5);pwStream.close();
}catch (FileNotFoundException e) {
i l ( i h i fil !
Closing a file
System.out.println("Error opening the input file!" + e.getMessage());
System.exit(0);}}catch (IOException e) {
System.out.println("IO Error!" + e.getMessage());e printStackTrace();
15
e.printStackTrace();System.exit(0);
}}}
![Page 16: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/16.jpg)
Program Input and Output(After execution the file data txt(After execution, the file data.txt contains:)Number = 0Number = 5Number = 10Number = 15Number = 20
16
![Page 17: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/17.jpg)
Input Stream Classes for Reading Text Files
Class Description MethodsClass Description Methods
FileReader Provides the basic stream for read(),character-by-character input.
(),close()
ff d d P id i b ff i i d()BufferedReader Provides input buffering to improve performance. Provides both character-by-
read(), readLine(), close()
character and line-by-line input.
17
![Page 18: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/18.jpg)
Reading Text Files using the class BufferedReaderimport java.io.*;import java.io. ;public class ReadingTextFiles {
public static void main(String[] args) {try {y {
FileReader frStream = new FileReader("data.txt");BufferedReader brStream =
new BufferedReader (frStream);String inputLine;int i;System.out.println("The file contains:");for (i=0; i<5; i++) {
inputLine = brStream.readLine(); // read in a lineSystem.out.println(inputLine);
}}brStream.close();
}t h (Fil N tF dE ti ) {catch (FileNotFoundException e) {System.out.println("Error opening the input file!" +
e.getMessage());System exit(0);
18
System.exit(0);}
![Page 19: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/19.jpg)
Reading Text Files using the class BufferedReader
catch (IOException e) {System.out.println("IO Error!" + e.getMessage());
e.printStackTrace();S t it(0)System.exit(0);
}}
}}
Program Input and Outputh fil iThe file contains:Number = 0Number = 5Number = 5Number = 10Number = 15Number = 20
19
![Page 20: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/20.jpg)
Using the StringTokenizer Classimport java.io.*;i j il * // d d f i k iimport java.util.*; // needed for StringTokenizerpublic class ReadingTextFiles2 {
public static void main(String[] args) {t {try {
BufferedReader brStream = new BufferedReader(new FileReader("data.txt"));
String inputLine str1 str2;String inputLine, str1, str2;int i, value;System.out.println("The file contains:");for (i=0; i<5; i++) { R d i li dfor (i=0; i<5; i++) {inputLine = brStream.readLine();StringTokenizer aString =
new StringTokenizer(inputLine);
Read in a line, and Use StringTokenizer to
break it down into new StringTokenizer(inputLine);str1 = aString.nextToken();str2 = aString.nextToken();value = Integer.parseInt(aString.nextToken());
words
g p ( g ())System.out.println("str1: " + str1 + " str2: " +
str2 + " value: " + value);}
20brStream.close();
}
![Page 21: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/21.jpg)
Using the StringTokenizer Class
catch (FileNotFoundException e) {catch (FileNotFoundException e) {System.out.println("Error opening the input file!" +
e.getMessage());System exit(0);System.exit(0);
}catch (IOException e) {
System.out.println("IO Error!" + e.getMessage());System.out.println( IO Error! + e.getMessage());e.printStackTrace();System.exit(0);
}}}
}
Program Input and OutputProgram Input and OutputThe file contains:str1: Number str2: = value: 0str1: Number str2: = value: 5str1: Number str2: = value: 10t 1 N b t 2 l 15
21
str1: Number str2: = value: 15str1: Number str2: = value: 20
![Page 22: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/22.jpg)
Reading File Names from the Keyboardi j ilimport java.util.Scanner; import java.io.*;public class ReadingTextFiles3 {
bli t ti id i (St i [] ) {public static void main(String[] args) {String fileName;Scanner sc = new Scanner(System.in);System out println("Enter the file name: ");System.out.println( Enter the file name: );fileName = sc.nextLine();try {
BufferedReader brStream = new BufferedReaderBufferedReader brStream = new BufferedReader (new FileReader(fileName));
String inputLine;int i;int i;System.out.println("The file contains:");for (i=0; i<5; i++) {inputLine = brStream.readLine();p ()System.out.println(inputLine);
}brStream.close();
22}
![Page 23: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/23.jpg)
catch (FileNotFoundException e) {System.out.println("Error opening the input file!" + fileName);
System.exit(0);}catch (IOException e) {System.out.println("IO Error!" + fileName);e.printStackTrace();
System.exit(0);}
}}P I t d O t tProgram Input and OutputEnter the file name: data.txtdata.txtThe file contains:Number = 0Number = 5Number = 10Number = 15
23
Number = 15Number = 20
![Page 24: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/24.jpg)
Testing for End of File
We use end-of-file indicator to test the end of a file.
Wh i th th d dLi () When using the method – readLine()- We test the special value null
When using the method – read()- We test the special value -1
These two methods will not throw EOFException
24
![Page 25: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/25.jpg)
Unbuffered I/O And End of File Testingimport java.util.Scanner;import java.io.*;po t ja a. o. ;public class FileCopying {
public static void main(String[] args) throws IOExceptionIOException
{int ch; Scanner sc = new Scanner(System.in);S stem o t println("Enter the inp t file name ")System.out.println("Enter the input file name: ");String fileName1 = sc.nextLine();System.out.println("Enter the output file name: ");String fileName2 = sc.nextLine();FileReader frStream = new FileReader(fileName1);FileWriter fwStream = new FileWriter(fileName2);System.out.println("The file contains:");while ((ch=frStream.read()) != -1) {
System.out.print((char)ch); When using read,f 1
y p (( ) );fwStream.write((char)ch);
}frStream close();
test for -1
When using readLine,
25
frStream.close();fwStream.close();
}}
When using readLine, test for null
![Page 26: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/26.jpg)
Program Input and OutputEnter the input file name: data.txtEnter the output file name:Enter the output file name:output.txtThe file contains:e e co ta s:Number = 0Number = 5Number = 10Number = 15Number = 20Number = 20
26
![Page 27: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/27.jpg)
Example: Using readLineimport java.util.Scanner;import java io *;import java.io.*;public class FileCopying2 {
public static void main(String[] args) throws IOException{{int ch; Scanner sc = new Scanner(System.in);String fileName1 = sc.nextLine();String fileName2 = sc.nextLine();BufferedReader brStream = new BufferedReader(new FileReader(fileName1));
PrintWriter pwStream = new PrintWriter(new BufferedWriter(new FileWriter(fileName2)));
System.out.println("The file contains:");System.out.println( The file contains: );String aString = brStream.readLine();while (aString != null) {
System out println(aString);System.out.println(aString);pwStream.println(aString);aString = brStream.readLine(); }
b St l () St l ()27
brStream.close(); pwStream.close();}
}
![Page 28: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/28.jpg)
Program Input and OutputEnter the input file name: data.txtEnter the output file name:Enter the output file name:output.txtThe file contains:e e co ta s:Number = 0Number = 5Number = 10Number = 15Number = 20Number = 20
28
![Page 29: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/29.jpg)
Chapter 14Chapter 14File Input/Output
• Streams and Files• File Stream Processing• Text File I/O• Text File I/O• The File Class• Binary File I/O
29
![Page 30: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/30.jpg)
The File Class- Obtaining information about a file or a directory
Method Descriptionexists() Returns a boolean true if the file exists.
g y
()
isDirectory() Returns a boolean true if the file is a directory.isFile() Returns a boolean true if the file is a file.canRead() Returns a boolean true if the file can be read from.canWrite() Returns a boolean true if the file exists and can be written
to.to.delete() Deletes the designated file. Returns a boolean true if the
delete operation is successful.() h fil f h fil f h i hgetName() Returns the file name of the file from the given pathname.
getAbsolutePath() Returns the complete absolute file or directory name represented by the File objectrepresented by the File object.
getParent() Returns the pathname of the parent directory of the file from the given pathname.
30length() Returns the size of the file, in bytes.renameTo() Renames the file. This method returns a boolean true if
the operation is successful
![Page 31: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/31.jpg)
Using the File Classimport java.io.*;import java.util.Scanner;public class UsingFileClass {public class UsingFileClass {
public static void main(String[] args) {Scanner sc = new Scanner(System.in);System out println("Enter the file name: ");System.out.println( Enter the file name: );String fileName = sc.nextLine();File aFile = new File(fileName);S t t i tl ("T t i t " + Fil i t ())System.out.println("Test exists = " + aFile.exists());System.out.println("Test isDirectory = " + aFile.isDirectory());
System.out.println("Test isFile = " + aFile.isFile());System.out.println("Test canRead = "+aFile.canRead());System.out.println("Test canWrite="+aFile.canWrite());System.out.println("Test getName="+aFile.getName());System.out.println("Test getAbsolutePath = “ + aFile.getAbsolutePath());aFile.getAbsolutePath());
System.out.println("Test getParent = " + aFile.getParent());
System out println("Test length = " + aFile length()
31
System.out.println( Test length = + aFile.length()+ " bytes");
}}
![Page 32: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/32.jpg)
Program Input and OutputEnter the file name: Java.txtTest exists = falseTest exists = falseTest isDirectory = falseTest isFile = falseest s e a seTest canRead = falseTest canWrite = falseTest getName = Java.txt Test getAbsolutePath = C:\Java.txtTest getParent = nullTest getParent = nullTest length = 0 bytes
32
![Page 33: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/33.jpg)
Checking Input File Name
import java.io.*;import java.util.Scanner;public class CheckFileReading {
public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.println("Enter the file name: ");y p ( );String fileName = sc.nextLine();File inFile = new File(fileName);while ((!inFile exists()) || (!inFile canRead())) {while ((!inFile.exists()) || (!inFile.canRead())) {
if (!inFile.exists())System.out.println("File not exist!");
else if (!inFile canRead())else if (!inFile.canRead())System.out.println("File can’t be read!");
System.out.println("Enter the file name again: ");fil i ()fileName = sc.nextLine();inFile = new File(fileName);
}
33
![Page 34: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/34.jpg)
Checking Input File Name
try {try {BufferedReader brStream = new BufferedReader(
new FileReader(fileName));String inputLine;String inputLine;int i;System.out.println("The file contains: ");f (i 0 i<5 i++) {for (i=0; i<5; i++) {
inputLine = brStream.readLine();System.out.println(inputLine);
}brStream.close();
}catch (IOException e) {
System.out.println("IO Error!" + e.getMessage());e.printStackTrace();e.printStackTrace();System.exit(0);
}}
34
}}
![Page 35: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/35.jpg)
Program Input and OutputEnter the file name: file1.txtFile not exist!File not exist! Enter the file name again: output.txtoutput.t tThe file contains:Number = 0Number = 5Number = 10Number = 15Number = 15Number = 20
35
![Page 36: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/36.jpg)
Checking Output File Nameimport java.io.*;import java.util.Scanner;public class CheckFileWriting {
public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.println("Enter the file name: ");String fileName = sc.nextLine();g ();File outFile = new File(fileName);
// check existence// check existenceif (outFile.exists()) {
System.out.println("File " + fileName + " currently exists ");" currently exists.");
System.out.print("Overwrite the file? (y/n): ");String inputAns = sc.next();h i h (0)char ans = inputAns.charAt(0);
if (ans == ’n’)System.exit(0);
36}
![Page 37: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/37.jpg)
try {PrintWriter pwStream = new PrintWriter(PrintWriter pwStream = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));int num;f ( 0 <5 ++) {for (num=0; num<5; num++) {
pwStream.println("Number = " + num*5);}pwStream.close();
}catch (IOException e) {
System.out.println("IO Error!" +e.getMessage());System.exit(0);
}}}
}
37
![Page 38: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/38.jpg)
Program Input and OutputEnter the file name: output.txtFile output1 txt currently existsFile output1.txt currently exists. Overwrite the file? (y/n): n
Enter the file name: output.txtFile output1.txt currently exists. Overwrite the file? (y/n): y(After execution the file output txt(After execution, the file output.txt contains)Number = 0Number = 5Number = 10
38Number = 15Number = 20
![Page 39: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/39.jpg)
Chapter 14Chapter 14File Input/Output
• Streams and Files• File Stream Processing• Text File I/O• Text File I/O• The File Class• Binary File I/O
39
![Page 40: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/40.jpg)
Binary File I/OBinary File I/O
Stream classStream class hierarchy
40
![Page 41: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/41.jpg)
Output Stream Classes for Writing Binary Files
Class Description Methods
FileOutputStream Provides the basic stream for t t t t
write(), flush(), l ()text output. close()
BufferedOutputStream Provides output buffering to improve performance.
write(), flush(), close()
ObjectOutputStream Provides a number of useful output methods for processing.
writeByte(), writeBoolean(), writeBytes(), p g y (),writeChar(), writeChars(), writeDouble(), writeFloat(), writeInt(), writeLong(), writeShort(),writeUTF(), flush(), close()
41
![Page 42: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/42.jpg)
Using the Class ObjectOutputStream to Write Binary Data
import java.io.*;import java.util.Scanner;public class WritingBinaryData {p g y {
public static void main(String[] args) {String fileName = " ";try {y
String name;int age;double height;Scanner sc = new Scanner(System.in);System.out.println("Enter the file name: ");fileName = sc.nextLine();FileOutputStream foStream =
new FileOutputStream(fileName);BufferedOutputStream boStream =
B ff dO t tSt (f St )new BufferedOutputStream(foStream);ObjectOutputStream doStream =
new ObjectOutputStream(boStream);int i;
42
int i;
![Page 43: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/43.jpg)
for (i=0; i<3; i++) {System.out.print("Enter name: ");
t()name = sc.next(); System.out.print("Enter age: ");age = sc.nextInt();System out print("Enter height: ");System.out.print("Enter height: ");height = sc.nextDouble();doStream.writeUTF(name); // namedoStream writeInt(age); // agedoStream.writeInt(age); // agedoStream.writeDouble(height); // height
}System out println("Writing completed!");System.out.println( Writing completed! );doStream.close();
}catch (FileNotFoundException e) {( p ) {
System.out.println("IOError: File not found!"+ fileName);System.exit(0);
}catch (IOException e) {
System.out.println("File IO Error!" + e.getMessage());System.exit(0);
43}
}}
![Page 44: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/44.jpg)
Program Input and OutputEnter the file name:binary.datEnter name: JunrongEnter name: JunrongEnter age: 16Enter height: 1.76te e g t: . 6Enter name: ChooEngEnter age: 17Enter height: 1.77Enter name: MayLingEnter age: 18Enter age: 18Enter height: 1.78Writing completed!g p
44
![Page 45: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/45.jpg)
Method Description
ObjectOutputStream Methods
writeByte(int b) Writes the byte b to the data output stream.
writeBoolean(boolean b) Writes the boolean b to the data output stream.
writeBytes(String s) Writes the String s to the data output stream as a sequence ofwriteBytes(String s) Writes the String s to the data output stream as a sequence ofbytes.
writeChar(int c) Writes the char c to the data output stream as a 2-byte Unicodevaluevalue.
writeChars(String s) Writes the String s to the data output stream as a sequence ofcharacters. Each character is written as 2-byte Unicode value.
writeDouble(double d) Writes the double d to the data output stream using 8 bytes.
writeFloat(float f) Writes the float f to the data output stream using 4 bytes.
it I t(i t i) W it th i t i t th d t t t t i 4 b twriteInt(int i) Writes the int i to the data output stream using 4 bytes.
writeLong(long l) Writes the long l to the data output stream using 8 bytes.
writeShort(short s) Writes the short s to the data output stream using 2 bytes.( ) p g y
writeUTF(String s) Writes the String s to the data output stream. UTF is aparticular encoding method for the string.
flush() Fl shes the o tp t stream to force an b ffered o tp t b tes to be
45
flush() Flushes the output stream to force any buffered output bytes to bewritten to the file.
close() Closes the file output stream connection.
![Page 46: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/46.jpg)
Cl D i ti M th d
Input Stream Classes for Reading Binary FilesClass Description Methods
FileInputStream Provides the basic stream
read(), close()basic stream for byte-based input.
BufferedInputStream Provides input buffering to
read(), close()
gimprove performance.
Obj tI tSt P id dB t ()ObjectInputStream Provides a number of useful input
readByte(), readBoolean(), readChar(),
methods for processing.
readDouble(), readFloat(), readInt(), readLong(),
46readShort(),readUTF(), close()
![Page 47: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/47.jpg)
Using the Class ObjectInputStream to Read Binary Dataimport java.util.Scanner;import java.util.Scanner;import java.io.*;public class ReadingBinaryData1 {
public static void main(String[] args) {p ( g[] g ) {String fileName = " ";try {
String name;int age;double height;Scanner sc = new Scanner(System.in);
System.out.println("Enter the file name: ");fileName = sc.nextLine();il fiFileInputStream fiStream = new FileInputStream(fileName);
BufferedInputStream biStream = B ff dI tSt (fiSt )new BufferedInputStream(fiStream);
ObjectInputStream diStream = new ObjectInputStream(biStream);
int i;
47
int i;
![Page 48: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/48.jpg)
Using the Class ObjectInputStream to Read Binary Data
for (i=0; i < 3; i++) {System.out.print("Name: ");System.out.println(name = diStream.readUTF());System.out.print("Age: ");System.out.println(age = diStream.readInt());System.out.print("Height: ");System.out.println(height= diStream.readDouble());
}diStream.close();
}}catch (FileNotFoundException e) {
System.out.println("IOError: File not found!"+ fileName);System exit(0);System.exit(0);
}catch (IOException e) {
System out println("File IO Error!" + e getMessage());System.out.println( File IO Error! + e.getMessage());System.exit(0);
}}
48
}}
![Page 49: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/49.jpg)
Program Input and OutputEnter the file name:binary.datName: JunrongName: JunrongAge: 16Height: 1.76e g t: . 6Name: ChooEngAge: 17Height: 1.77Name: MayLingAge: 18Age: 18Height: 1.78
49
![Page 50: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/50.jpg)
M th d D i ti
ObjectInputStream Class Methods
Method Description
readByte() Reads a byte from the data input stream.
readBoolean() Reads a boolean from the data input stream.
readChar() Reads a char (2 bytes) from the data input stream.
readDouble() Reads a double (8 bytes) from the data input stream.
readFloat() Reads a float (4 bytes) from the data input stream.readFloat() Reads a float (4 bytes) from the data input stream.
readInt() Reads an int (4 bytes) from the data input stream.
readLong() Reads a long (8 bytes) from the data input streamreadLong() Reads a long (8 bytes) from the data input stream.
readShort() Reads a short (2 bytes) from the data input stream.
dUTF() R d St i l f th d t i t treadUTF() Reads a String value from the data input stream.
close() Closes the file input stream connection.
50
![Page 51: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/51.jpg)
Reading Binary Data with End of File Testingimport java.io.*;import java.util.Scanner;public class ReadingBinaryData2 {
public static void main(String[] args) {String fileName = " ";try {
String name;i tint age;double height;Scanner sc = new Scanner(System.in);
System.out.println("Enter the file name: ");fileName = sc.nextLine();FileInputStream fiStream =FileInputStream fiStream =
new FileInputStream(fileName);BufferedInputStream biStream =
new BufferedInputStream(fiStream);new BufferedInputStream(fiStream);ObjectInputStream diStream =
new ObjectInputStream(biStream);int i;
51
;
![Page 52: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/52.jpg)
try {while (true) {
1:2:
When reading beyond the file, an end-of-file Exception (EOFException) is thrownUse end-of-file exception for testing end-of-filewhile (true) {
System.out.print("Name: ");System.out.println(name = diStream.readUTF());System out print("Age: ");
2: p g
System.out.print( Age: );System.out.println(age = diStream.readInt());System.out.print("Height: ");System out println(height= diStream readDouble());System.out.println(height diStream.readDouble());
}}catch (EOFException e) {} // or IOException3: ( p ) {} // pdiStream.close();
}catch (FileNotFoundException e) {
3:to catch the end-of-file exceptionp
System.out.println("IOError: File not found!"+ fileName);System.exit(0);
}catch (IOException e) {
System.out.println("File IO Error!" + e.getMessage());System.exit(0);
N t ifi t h bl k fi t th52
}}
}
Note more specific catch blocks first, then the general one
![Page 53: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/53.jpg)
Program Input and OutputEnter the file name:binary.datName: JunrongName: JunrongAge: 16Height: 1.76e g t: . 6Name: ChooEngAge: 17Height: 1.77Name: MayLingAge: 18Age: 18Height: 1.78
53
![Page 54: Chapter 14Chapter 14 File Input/Output · PDF fileAdvantage: the programmer does not need to write Input Stream Keyboard Display Output Stream the programmer does not need to write](https://reader034.vdocuments.mx/reader034/viewer/2022051320/5aa71d0c7f8b9a424f8be9bf/html5/thumbnails/54.jpg)
Chapter 14Chapter 14File Input/Output
• Streams and Files• File Stream Processing• Text File I/O• Text File I/O• The File Class• Binary File I/O
54