UNRESTRICTED
ITSD004
Programming Fundamentals
© 2022 Singapore Institute of Management Group Limited
Learning Outcomes
After studying this chapter and the recommended reading, you
should be able to:
• Topic 19
• Create, read, write and update files
• Distinguish the differences between text files and binary files
• Use class Formatter to output text to a file
• Use class Scanner to input text from a file
Introduction
Data stored in variables and arrays is temporary, it’s lost
when a local variable goes out of scope or when the
program terminates.
For long-term retention of data, even after the
programs that create the data terminate, computers
use files.
3
Introduction
You use files every day for tasks such as writing a
document or creating a spreadsheet.
Computers store files on secondary storage devices,
including hard disks, flash drives, DVDs and more.
Data maintained in files is persistent data as it exists
beyond the duration of program execution.
4
Files and Streams
Java views each file as a sequential stream of bytes.
Every operating system provides a mechanism to
determine the end of a file.
Such as an end-of-file marker or a count of the total
bytes in the file that’s recorded in a system maintained
administrative data structure.
5
Files and Streams
Java’s view of a file of n bytes.
A Java program processing a stream of bytes simply
receives an indication from the operating system when
it reaches the end of the stream.
6
Files and Streams
File streams can be used to input and output data as
bytes or characters.
This introduces TWO (2) kind of streams:
1. Byte-Based streams
2. Character-Based streams
7
Files and Streams
Byte-Based Streams
Byte-based streams output and input data in its binary
format.
- A char is two bytes
- An int is four bytes
- A double is eight bytes
8
Files and Streams
Byte-Based Streams
Files created using byte-based streams are binary files.
Binary files are read by programs that understand the
file’s specific content and its ordering.
9
Files and Streams
Byte-Based Streams
Example of a Binary file:
10
Files and Streams
Character-Based Streams
Output and input data as a sequence of characters in
which every character is two bytes.
The number of bytes for a given value depends on the
number of characters in that value.
11
Files and Streams
Character-Based Streams
For example:
The value 2000000000 requires 20 bytes (10 characters
at two bytes per character)
The value 7 requires only two bytes (1 character at two
bytes per character).
12
Files and Streams
Standard Input, Output and Error Streams
A Java program opens a file by creating an object and
associating a stream of bytes or characters with it.
The object’s constructor interacts with the operating
system to open the file.
Java can also associate streams with different devices.
13
Files and Streams
Standard Input, Output and Error Streams
When a Java program begins executing, it creates
THREE (3) stream objects that are associated with
devices:
1. System.in (standard input stream)
2. System.out (standard output stream)
3. System.err (standard error stream)
14
Files and Streams
Standard Input, Output and Error Streams
1. System.in (standard input stream)
Enables a program to input bytes from the
keyboard.
2. System.out (standard output stream)
Enables a program to output character data to the
screen.
15
Files and Streams
Standard Input, Output and Error Streams
3. System.err (standard error stream)
Enables a program to output character-based error
messages to the screen.
16
Files and Streams
Standard Input, Output and Error Streams
Each stream can be redirected.
For System.in, this capability enables the program to
read bytes from different source.
For System.out and System.err, it enables the output
to be sent to a different location, such as a file on disk.
17
InputStream and OutputStream
Java provides TWO (2) object class to read from files
and write on files.
1. InputStream
Used to read data from a source.
2. OutputStream
Used for writing data to a destination.
18
InputStream and OutputStream
Both InputStream and OutputStream are subclasses of
the Object class.
19
Create, Read and Write Files
FileInputStream
This stream is used for reading data from the files.
Objects can be created using the keyword new and
there are several types of constructors available.
20
Create, Read and Write Files
FileInputStream
Following constructor takes a file name as a string to
create an input stream object to read the file.
InputStream f = new FileInputStream(“C:/User/Desktop/test.txt");
21
Create, Read and Write Files
FileInputStream
Following constructor takes a file object to create an
input stream object to read the file.
We will create a file object using File() method:
File f = new File("C:/User/Desktop/test.txt");
InputStream f = new FileInputStream(f);
22
Create, Read and Write Files
FileInputStream Methods
1. public void close() throws IOException{}
– This method closes the file output stream.
– Releases any system resources associated with the
file.
– Throws an IOException.
23
Create, Read and Write Files
FileInputStream Methods
2. protected void finalize() throws IOException {}
– This method cleans up the connection to the file.
– Ensures that the close method of this file
outputstream is called when there are no more
references to this stream.
– Throws an IOException.
24
Create, Read and Write Files
FileInputStream Methods
3. public int read(int r) throws IOException{}
– This method reads the specified byte of data from
the InputStream.
– Returns an int.
– Returns the next byte of data and -1 will be
returned if it's the end of the file.
25
Create, Read and Write Files
FileInputStream Methods
4. public int read(byte[] r) throws IOException{}
– This method reads r.length bytes from the input
stream into an array.
– Returns the total number of bytes read.
– If it is the end of the file, -1 will be returned.
26
Create, Read and Write Files
FileInputStream
Example to read contents from a file:
ReadfromFile.java
Part 1
import java.io.*;
public class ReadfromFile{
public static void main(String args[]){
try{
FileInputStream fin = new FileInputStream(“test.txt”);
int i=0;
27
Create, Read and Write Files
FileInputStream
ReadfromFile.java
Part 2
while((i=fin.read())!=-1){
System.out.println((char)i);
}
fin.close();
} catch(Exception e){
System.out.println(e);
}
}
}
}
28
Create, Read and Write Files
BufferedReader
Used to read the text from a character-based input
stream.
It can be used to read data line by line by readLine()
method.
It makes the performance fast.
29
Create, Read and Write Files
BufferedReader
Here is an example:
ReadfromFileBuffered.java
Part 1
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadfromFileBuffered {
public static void main(String[] args) {
try {
FileReader reader = new FileReader(“test.txt");
30
Create, Read and Write Files
BufferedReader
ReadfromFileBuffered.java
Part 2
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
31
Create, Read and Write Files
FileOutputStream
FileOutputStream is used to create a file and write data
into it.
The stream would create a file, if it doesn't already
exist, before opening it for output.
32
Create, Read and Write Files
FileOutputStream
Following constructor takes a file name as a string to
create an input stream object to write the file:
OutputStream f = new FileOutputStream("C:/User/Desktop/test.txt") ;
33
Create, Read and Write Files
FileOutputStream
Following constructor takes a file object to create an
output stream object to write the file.
We will create a file object using File() method:
File f = new File("C:/User/Desktop/test.txt");
OutputStream f = new FileOutputStream(f);
34
Create, Read and Write Files
FileOutputStream Methods
1. public void close() throws IOException{}
– This method closes the file output stream.
– Releases any system resources associated with the
file.
– Throws an IOException.
35
Create, Read and Write Files
FileOutputStream Methods
2. protected void finalize() throws IOException {}
– This method cleans up the connection to the file.
– Ensures that the close method of this file output
stream is called when there are no more
references to this stream.
– Throws an IOException.
36
Create, Read and Write Files
FileOutputStream Methods
3. public void write(int w)throws IOException{}
– This methods writes the specified byte to the
output stream.
37
Create, Read and Write Files
FileOutputStream Methods
4. public void write(byte[] w)
– Writes w.length bytes from the mentioned byte array to
the OutputStream.
38
Create, Read and Write Files
FileOutputStream Methods
Example to write contents to a file:
WritetoFile.java
Part 1
import java.io.*;
public class WritetoFile {
public static void main(String args[]){
try {
FileOutpuStream fo=new FileOutputStream(“hello.txt”);
String i=”Hello Intellipaat “;
byte b[]=i.getBytes(); //converting string into byte array
39
Create, Read and Write Files
FileOutputStream Methods
WritetoFile.java
Part 2
fo.write(i);
fo.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
}
40
Create, Read and Write Files
BufferedWriter Methods
Used to provide buffering for Writer instances.
It makes the performance fast.
It inherits Writer class.
The buffering characters are used for providing the efficient
writing of single arrays, characters, and strings.
41
Create, Read and Write Files
BufferedWriter Methods
Here is an example:
WritetoFileBuffered.java
Part 1
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class WritetoFileBuffered {
public static void main(String[] args) {
try {
42
Create, Read and Write Files
BufferedWriter Methods
WritetoFileBuffered.java
Part 2
FileWriter writer = new FileWriter(“test.txt", true);
BufferedWriter bufferedWriter = new BufferedWriter(writer);
bufferedWriter.write(“Welcome to DIT");
bufferedWriter.newLine();
bufferedWriter.write(“Awesome!");
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
43
Formatter Class
Provides support for layout justification and alignment,
common formats for numeric, string, and date/time
data, and locale-specific output.
Primarily uses the String .format() method.
Similar to the printf, where we use the various format
symbols such as %s, %n, %f, etc..
44
Formatter
Here’s a short example on how we use the .format()
method.
FormatterSample.java
Part 1
public class FormatterSample {
public static void main(String args[]){
String name="sonoo";
String sf1=String.format("name is %s",name);
String sf2=String.format("value is %f",32.33434);
String sf3=String.format("value is %32.12f",32.33434);//returns 12
char fractional part filling with 0
45
Formatter
Here’s a short example on how we use the .format()
method.
FormatterSample.java
Part 2
System.out.println(sf1);
System.out.println(sf2);
System.out.println(sf3);
}
}
46
Formatter
Let’s try out an example that uses the .format() method
to format texts and add them in a file.
FormatterWritetoFile.java
Part 1
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.Logger;
47
Formatter
FormatterWritetoFile.java
Part 2
public class FormatterWritetoFile {
public static void main(String[] args) {
// TODO code application logic here
// Let's write the formatted output to C:\xyz.text file
FileWriter writer;
String str1 = String.format("%d", 101);
String str2 = String.format("|%10d|", 101); // Specifying length of integer
String str3 = String.format("|%-10d|", 101); // Left-justifying within the
specified width
String str4 = String.format("|% d|", 101);
String str5 = String.format("|%010d|", 101); // Filling with zeroes
try {
writer = new FileWriter("formattext.txt", true);
BufferedWriter bufferedWriter = new BufferedWriter(writer);
48
Formatter
FormatterWritetoFile.java
Part 3
bufferedWriter.write(str1);
bufferedWriter.newLine();
bufferedWriter.write(str2);
bufferedWriter.newLine();
bufferedWriter.write(str3);
bufferedWriter.newLine();
bufferedWriter.write(str4);
bufferedWriter.newLine();
bufferedWriter.write(str5);
bufferedWriter.close();
} catch (IOException ex) {
49
Formatter
FormatterWritetoFile.java
Part 4
Logger.getLogger(FormatterWritetoFile.class.getName()).log(Level.SEVERE,
null, ex);
}
}
}
50
Using the Scanner object to key text from a File
The Scanner object class allows us to receive user
inputs from the keyboard.
We can also use the Scanner object to read from a file
and print it out.
The next example, demonstrates just that.
51
Using the Scanner object to key text from a File
ReadFileUsingScanner.java
Part 1
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class ReadFileUsingScanner {
public static void main(String[] args) throws IOException {
//Write content to file
writeFileContents();
//Reading content of file using Scanner class
readFileContents();
}
52
Using the Scanner object to key text from a File
ReadFileUsingScanner.java
Part 2
private static void writeFileContents() throws IOException {
try (FileWriter fileWriter = new FileWriter("info.txt")) {
fileWriter.write("10 ");
fileWriter.write("20.5 ");
fileWriter.write("Employee ");
fileWriter.write("50.00 ");
fileWriter.write("Coffee");
}
}
private static void readFileContents() throws IOException {
System.out.println("Reading contents of file using Scanner class:");
53
Using the Scanner object to key text from a File
ReadFileUsingScanner.java
Part 3
try (FileReader fileReader = new FileReader("info.txt");
Scanner scanner=new Scanner(fileReader)){
while (scanner.hasNext()) {
if(scanner.hasNextInt()) {
System.out.println(scanner.nextInt());
} else if(scanner.hasNextDouble()) {
System.out.println(scanner.nextDouble());
} else if(scanner.hasNext()) {
System.out.println(scanner.next());
}
}
}
}
}
54
Using the Scanner object to key text from a File
ReadFileUsingScanner.java
Perform a while iteration to read each line of text from
the info.txt.
55
Reading
Textbook:
Deitel, H., & Deitel, P. J. (2017). Java How to Program. Early Objects (11th ed.).
Pearson. ISBN: 978-0134751962
Reference:
Topic 19 – Files I/O
END OF LESSON
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )